Created
December 10, 2013 22:23
-
-
Save zgohr/7901403 to your computer and use it in GitHub Desktop.
Basic django class based JSON view that can handle JSONP callbacks
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
from django.http import HttpResponse | |
from django.views import generic | |
import json | |
class JSONView(generic.View): | |
callback_parameter = 'callback' | |
def get_json_data(self, request, *args, **kwargs): | |
""" | |
Implement this function to return the object to be serialized | |
""" | |
raise NotImplementedError | |
def get(self, request, *args, **kwargs): | |
data = self.get_json_data(request, *args, **kwargs) | |
callback = request.GET.get(self.callback_parameter) | |
if callback: | |
response = HttpResponse("%s(%s);" % (callback, json.dumps(data)), | |
content_type='text/javascript') | |
else: | |
response = HttpResponse(json.dumps(data), | |
content_type='application/json') | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment