Login

JSON decorator for views handling ajax requests

Author:
anilshanbhag
Posted:
December 23, 2012
Language:
Python
Version:
1.4
Score:
1 (after 1 ratings)

Sample usage for using decorator @json_response(ajax_required=True, login_required=True) def subscribe(request): return {"status":"success"}

Converts a function returning dict into json response. Does is_ajax check and user authenticated check if set in flags. When function returns HttpResponse does nothing.

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

Comments

Please login first before commenting.