Skip to content

Instantly share code, notes, and snippets.

@heyman
Created September 18, 2012 16:12
Show Gist options
  • Save heyman/3744010 to your computer and use it in GitHub Desktop.
Save heyman/3744010 to your computer and use it in GitHub Desktop.
Generic Django JSON view class with JSONP support
try:
import simplejson as json
except ImportError:
import json
from django.views import generic
from django.http import HttpResponse
class JsonView(generic.View):
"""
Generic view for returning JSON data.
Supports JSONP through the query variable `callback` (used by jQuery)
Usage:
Override get_json_data to return the data that is to be encoded
or:
JsonView.as_view(json_data={"foo": "bar"})
"""
json_data = {}
def get_json_data(self, request, *args, **kwargs):
"""
Should return the data that is to be JSON encoded and sent to the client
"""
return self.json_data
def get(self, request, *args, **kwargs):
data = self.get_json_data(request, *args, **kwargs)
jsonp_callback = request.GET.get("callback")
if jsonp_callback:
response = HttpResponse("%s(%s);" % (jsonp_callback, json.dumps(data)))
response["Content-type"] = "text/javascript; charset=utf-8"
else:
response = HttpResponse(json.dumps(data))
response["Content-type"] = "application/json; charset=utf-8"
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment