Skip to content

Instantly share code, notes, and snippets.

@sivy
Created March 16, 2011 03:16
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save sivy/871954 to your computer and use it in GitHub Desktop.
Save sivy/871954 to your computer and use it in GitHub Desktop.
a jsonp view decorator for Django
def jsonp(f):
"""Wrap a json response in a callback, and set the mimetype (Content-Type) header accordingly
(will wrap in text/javascript if there is a callback). If the "callback" or "jsonp" paramters
are provided, will wrap the json output in callback({thejson})
Usage:
@jsonp
def my_json_view(request):
d = { 'key': 'value' }
return HTTPResponse(json.dumps(d), content_type='application/json')
"""
from functools import wraps
@wraps(f)
def jsonp_wrapper(request, *args, **kwargs):
resp = f(request, *args, **kwargs)
if resp.status_code != 200:
return resp
if 'callback' in request.GET:
callback= request.GET['callback']
resp['Content-Type']='text/javascript; charset=utf-8'
resp.content = "%s(%s)" % (callback, resp.content)
return resp
elif 'jsonp' in request.GET:
callback= request.GET['jsonp']
resp['Content-Type']='text/javascript; charset=utf-8'
resp.content = "%s(%s)" % (callback, resp.content)
return resp
else:
return resp
return jsonp_wrapper
@apg
Copy link

apg commented Mar 16, 2011

use functools.wraps instead of _view.name == view_func.name ...

It seems unnecessary to have _dec. You'd get the same results by removing it and making jsonp directly take view_func. You're not passing any arguments that are used within _view.

@sivy
Copy link
Author

sivy commented Mar 16, 2011

functools makes it a lot easier! esp now that I actually understand the idea of the decorator.

@sivy
Copy link
Author

sivy commented Mar 17, 2011

Note: unwrapped responses are 'application/json', once they're wrapped in a callback they're served as 'text'javascript'.

@Axexuxizozaz
Copy link

why output callback( b' {thejson} ' )?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment