Created
January 31, 2012 15:43
-
-
Save prestontimmons/1711148 to your computer and use it in GitHub Desktop.
Django json_view decorator
This file contains hidden or 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 functools import wraps | |
from json import dumps | |
from django.http import HttpResponse | |
def json_view(view_func): | |
@wraps(view_func) | |
def inner(request, *args, **kwargs): | |
response = view_func(request, *args, **kwargs) | |
if request.GET.get("format") == "json" and hasattr(response, "context_data"): | |
return HttpResponse( | |
dumps(response.context_data, sort_keys=True), | |
mimetype="application/json", | |
) | |
return response | |
return inner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment