*JsonWebService.jsonresponse
JsonWebService provides the property jsonresponse which marks the method it is applied to, and also serializes to json the response of the method.
*JsonWebService.urls Scans the marked methods and build a urlpattern ready to use in urls.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | ## ======= 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)),
)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.