Login

JSON View Decorator

Author:
bryanpieper
Posted:
July 11, 2010
Language:
Python
Version:
1.2
Tags:
json decorator
Score:
3 (after 3 ratings)

Django JSON view decorator. Dumps the object returned from the view function. Allows you to customize the JSON dumps() function using the available keyword arguments available from the simplejson module. By default, indents the output with 4 characters.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from functools import wraps
from django.http import HttpResponse
from django.utils import simplejson as json

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

More like this

  1. Using dojo/json to check for username availability by heckj 7 years, 10 months ago
  2. JSON view decorator by kcarnold 7 years, 1 month ago
  3. JSON decorator for views handling ajax requests by anilshanbhag 2 years, 4 months ago
  4. An XML-RPC Decorator by blinks 8 years, 1 month ago
  5. ajax protocol for data by limodou 8 years, 2 months ago

Comments

Please login first before commenting.