Login

base class to easily expose json based web services

Author:
jpablo
Posted:
July 21, 2010
Language:
Python
Version:
1.3
Tags:
json webservice
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. AjaxForm Base Classes by btaylordesign 4 years, 3 months ago
  2. JsonResponse by zakj 8 years, 3 months ago
  3. Class-based process form view. by I159 3 years, 7 months ago
  4. Simple templatetag to mark navigation as active using view names or regex by gluchet 2 years, 1 month ago
  5. Generic view mixing that allows output to JSON, HTML, HTML SNIPPETS by danielsokolowski 3 years, 11 months ago

Comments

Please login first before commenting.