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
34
35
36
37
38
|
from django.core.serializers import serialize
from django.http import HttpResponse
from django.utils.functional import Promise
from django.utils.encoding import force_text
import json as simplejson
class LazyEncoder(simplejson.JSONEncoder):
def default(self, obj):
if isinstance(obj, Promise):
return force_text(obj)
return obj
class JSONResponse(HttpResponse):
"""A simple subclass of ``HttpResponse`` which makes serializing to JSON
easy."""
def __init__(self, object, is_iterable=True):
if is_iterable:
content = serialize('json', object)
else:
content = simplejson.dumps(object, cls=LazyEncoder)
super(JSONResponse, self).__init__(
content, mimetype='application/json')
class XMLResponse(HttpResponse):
"""A simple subclass of ``HttpResponse`` which makes serializing to XML
easy."""
def __init__(self, object, is_iterable=True):
if is_iterable:
content = serialize('xml', object)
else:
content = object
super(XMLResponse, self).__init__(content, mimetype='application/xml')
|