Last active
January 2, 2016 21:09
-
-
Save victorono/8361639 to your computer and use it in GitHub Desktop.
return json from view 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import json | |
from functools import wraps | |
from django.http import HttpResponse | |
def render_to_json(**jsonargs): | |
""" | |
Renders a JSON response with a given returned instance. Assumes json.dumps() can | |
handle the result. The default output uses an indent of 4. | |
@render_to_json() | |
def a_view(request, arg1, argN): | |
... | |
return {'x': range(4)} | |
@render_to_json(indent=2) | |
def a_view2(request): | |
... | |
return [1, 2, 3] | |
""" | |
def outer(f): | |
@wraps(f) | |
def inner_json(request, *args, **kwargs): | |
result = f(request, *args, **kwargs) | |
r = HttpResponse(mimetype='application/json') | |
if result: | |
indent = jsonargs.pop('indent', 4) | |
r.write(json.dumps(result, indent=indent, **jsonargs)) | |
else: | |
r.write("{}") | |
return r | |
return inner_json | |
return outer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment