Skip to content

Instantly share code, notes, and snippets.

@vladimiroff
Created August 18, 2013 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladimiroff/6263141 to your computer and use it in GitHub Desktop.
Save vladimiroff/6263141 to your computer and use it in GitHub Desktop.
json_view and jsonp_view decorators for Django
import json
from django.http import HttpResponse
class JsonResponse(HttpResponse):
def __init__(self, content, status=None):
super(JsonResponse, self).__init__(json.dumps(content), status=status,
mimetype='application/json')
class JsonpResponse(HttpResponse):
def __init__(self, content, callback, status=None):
content = '%s(%s);' % (callback, json.dumps(content))
super(JsonpResponse, self).__init__(content, status=status,
mimetype='application/javascript')
def json_view(func):
def view(request, *args, **kwargs):
response = func(request, *args, **kwargs)
if isinstance(response, HttpResponse):
return response
return JsonResponse(response)
return view
def jsonp_view(func):
def view(request, *args, **kwargs):
response = func(request, *args, **kwargs)
if isinstance(response, HttpResponse):
return response
return JsonpResponse(response, callback=request.GET.get('callback'))
return view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment