## ======= file: ws.py ======== from django.http import HttpResponse from django.conf.urls.defaults import patterns from django.core import serializers class JsonResponse(HttpResponse): def __init__(self, content, *args, **kwargs): data = serializers.serialize("json", content) super(JsonResponse, self).__init__(data, mimetype="text/json", *args, **kwargs) class JsonWebService(object): ''' Base class for json-based web services ''' @staticmethod def jsonresponse(): def decorator(func): def wrap_json(*args): ret = func(*args) return JsonResponse(ret) wrap_json._is_json_ws = True return wrap_json return decorator @classmethod def getActions(cls): ''' returns the methods decorated with jsonresponse @param cls: ''' return filter(lambda k: getattr(getattr(cls, k), '_is_json_ws', False), dir(cls)) @property def urls(self): urls = [] for action in self.getActions(): urls.append((r'^json/' + action, getattr(self, action))) urlpatterns = patterns('', *urls) return urlpatterns ## example use of JsonWebService from django.contrib.comments.models import Comment class SMCommandWS(JsonWebService): @JsonWebService.jsonresponse() def getComments(self, request): 'the url will be /ws/json/getComments' return Comment.objects.all() ws = MySiteWS() ## ======== file: urls.py ====== from App.ws import ws ... urlpatterns += patterns('', (r'^ws/', include(ws.urls)), )