JSON decorator for views handling ajax requests

 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
from django.utils import simplejson
from django.http import HttpResponse

class json_response(object):
    def __init__(self, login_required = False, ajax_required = False):
        self.login_required = login_required
        self.ajax_required = ajax_required
    def __call__(self, func):
        class_args = self
        def decorator(request, *args, **kwargs):
            if class_args.login_required and not request.user.is_authenticated():
                objects = {
                    "status": "error",
                    "msg": "User not authenticated"
                }
            elif class_args.ajax_required and not request.is_ajax():
                objects = {
                    "status": "error",
                    "msg": "Request gone wrong :("
                }
            else:
                objects = func(request, *args, **kwargs)
            
            if isinstance(objects, HttpResponse):
                return objects
            try:
                data = simplejson.dumps(objects)
                if 'callback' in request.REQUEST:
                    # a jsonp response!
                    data = '%s(%s);' % (request.REQUEST['callback'], data)
                    return HttpResponse(data, "text/javascript")
            except:
                data = simplejson.dumps(str(objects))
            return HttpResponse(data, "application/json")
        
        return decorator

More like this

  1. Ajax required decorator by zenx 5 years, 11 months ago
  2. Auto rendering decorator with options by Batiste 6 years, 3 months ago
  3. Django JSONP Decorator by cominatchu 3 years, 6 months ago
  4. Format transition middleware by limodou 7 years, 1 month ago
  5. Render Decorator by dahool 4 years, 7 months ago

Comments

(Forgotten your password?)