Skip to content

Instantly share code, notes, and snippets.

@wonderbeyond
Forked from sivy/jsonp_decorator.py
Last active December 17, 2015 19:28
Show Gist options
  • Save wonderbeyond/5660199 to your computer and use it in GitHub Desktop.
Save wonderbeyond/5660199 to your computer and use it in GitHub Desktop.
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
callback = request.GET.get('callback') or request.GET.get('jsonp')
if callback:
resp['Content-Type']='text/javascript; charset=utf-8'
resp.content = "%s(%s)" % (callback, resp.content)
return resp
else:
return resp
return jsonp_wrapper
@wonderbeyond
Copy link
Author

resp.content = u"%s(%s)" % (callback, resp.content) ?

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