-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathresponse.py
38 lines (27 loc) · 1.15 KB
/
response.py
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
# encoding: utf-8
from django.http import HttpResponse
import json
MIMEANY = '*/*'
MIMEJSON = 'application/json'
MIMETEXT = 'text/plain'
def response_mimetype(request):
"""response_mimetype -- Return a proper response mimetype, accordingly to
what the client accepts, as available in the `HTTP_ACCEPT` header.
request -- a HttpRequest instance.
"""
can_json = MIMEJSON in request.META['HTTP_ACCEPT']
can_json |= MIMEANY in request.META['HTTP_ACCEPT']
return MIMEJSON if can_json else MIMETEXT
class JSONResponse(HttpResponse):
"""JSONResponse -- Extends HTTPResponse to handle JSON format response.
This response can be used in any view that should return a json stream of
data.
Usage:
def a_iew(request):
content = {'key': 'value'}
return JSONResponse(content, mimetype=response_mimetype(request))
"""
def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs):
json_opts = json_opts if isinstance(json_opts, dict) else {}
content = json.dumps(obj, **json_opts)
super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)