Django JSONP Decorator

 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
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required

class AllowJSONPCallback(object):
    """This decorator function wraps a normal view function                                                                                      
    so that it can be read through a jsonp callback.                                                                                             
                                                                                                                                                 
    Usage:                                                                                                                                       
                                                                                                                                                 
    @AllowJSONPCallback                                                                                                                          
    def my_view_function(request):                                                                                                               
        return HttpResponse('this should be viewable through jsonp')                                                                             
                                                                                                                                                 
    It looks for a GET parameter called "callback", and if one exists,                                                                           
    wraps the payload in a javascript function named per the value of callback.                                                                  
                                                                                                                                                 
    Using AllowJSONPCallback implies that the user must be logged in                                                                             
    (and applies automatically the login_required decorator).                                                                                    
    If callback is passed and the user is logged out, "notLoggedIn" is                                                                           
    returned instead of a normal redirect, which would be hard to interpret                                                                      
    through jsonp.                                                                                                                               
                                                                                                                                                 
    If the input does not appear to be json, wrap the input in quotes                                                                            
    so as not to throw a javascript error upon receipt of the response."""
    def __init__(self, f):
        self.f = login_required(f)

    def __call__(self, *args, **kwargs):
        request = args[0]
        callback = request.GET.get('callback')
        # if callback parameter is present,                                                                                                      
        # this is going to be a jsonp callback.                                                                                                  
        if callback:
            if request.user.is_authenticated():
                try:
                    response = self.f(*args, **kwargs)
                except:
                    response = HttpResponse('error', status=500)
                if response.status_code / 100 != 2:
                    response.content = 'error'
            else:
                response = HttpResponse('notLoggedIn')
            if response.content[0] not in ['"', '[', '{'] \
                    or response.content[-1] not in ['"', ']', '}']:
                response.content = '"%s"' % response.content
            response.content = "%s(%s)" % (callback, response.content)
            response['Content-Type'] = 'application/javascript'
        else:
            response = self.f(*args, **kwargs)
        return response

More like this

  1. Bootstrap button dropdown widget (replaces forms.Select) by benjaoming 1 year, 8 months ago
  2. Class-Based AJAX fallback view by fahhem 3 years, 3 months ago
  3. Admin Input Field Character Count via jQuery by joshman 5 years, 4 months ago
  4. Javascript Chain Select Widget by ogo 5 years, 10 months ago
  5. Pagination shortcut by piratus 5 years, 1 month ago

Comments

(Forgotten your password?)