Created
November 11, 2010 10:20
-
-
Save zacharyvoase/672308 to your computer and use it in GitHub Desktop.
JSONResponse for Django
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
# -*- coding: utf-8 -*- | |
import django.http | |
import simplejson as json | |
class JSONResponse(django.http.HttpResponse): | |
"""Represent a HTTP response with a Content-Type of 'application/json'. | |
This subclass of `django.http.HttpResponse` will remove most of the | |
necessary boilerplate in returning JSON responses from views. The object | |
to be serialized is passed in as the only positional argument, and the | |
other keyword arguments are as usual for `HttpResponse`, with one | |
exception: an optional 'callback' argument may be given which will wrap | |
the response with a JavaScript function call to the given function name. | |
""" | |
def __init__(self, obj, indent=0, **kwargs): | |
kwargs['content'] = json.dumps(obj, indent=indent) | |
if 'callback' in kwargs: | |
callback = kwargs.pop('callback') | |
if callback: | |
kwargs['content'] = u'%s(%s);' % (callback, kwargs['content']) | |
kwargs.setdefault('content_type', 'application/javascript') | |
kwargs.setdefault('content_type', 'application/json') | |
super(JSONResponse, self).__init__(**kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment