Skip to content

Instantly share code, notes, and snippets.

@fcurella
Created December 30, 2010 04:02
Show Gist options
  • Save fcurella/759436 to your computer and use it in GitHub Desktop.
Save fcurella/759436 to your computer and use it in GitHub Desktop.
A little decorator that allows you to return a dict in your views instead of render_to_response or HttpResponse or whatever. It respects the callback argument for proper JSONP action if you so choose.
from django.http import HttpResponse
from decorator import decorator
import simplejson as json
@decorator
def json_response(f, *args, **kwargs):
try:
status_code = 200
response = {
'status': True,
'data': f(*args, **kwargs)
}
except Exception, e:
status_code = 400
response = {
'status': False,
'message': '%s: %s' % (e.__class__.__name__, str(e))
}
body = json.dumps(response, indent=4)
if 'callback' in args[0].GET:
body = '%s(%s)' % (args[0].GET['callback'], body)
return HttpResponse(body, status=status_code)
@fcurella
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment