Created
December 30, 2010 04:02
-
-
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.
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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Originally by joestump at http://forrst.com/posts/Simple_JSON_response_decorator_for_Django-0Ns