Login

base class to easily expose json based web services

Author:
jpablo
Posted:
July 21, 2010
Language:
Python
Version:
1.3
Score:
-1 (after 1 ratings)

*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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.