Created
September 18, 2012 16:12
-
-
Save heyman/3744010 to your computer and use it in GitHub Desktop.
Generic Django JSON view class with JSONP support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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