|
1
|
|
|
from __future__ import absolute_import |
|
2
|
|
|
import json |
|
3
|
|
|
|
|
4
|
|
|
from django.core.serializers.json import DjangoJSONEncoder |
|
5
|
|
|
from django.http import HttpResponse |
|
6
|
|
|
from django.http.response import HttpResponseBadRequest |
|
7
|
|
|
|
|
8
|
|
|
from .utils import APPLICATION_JS, JSONP_TEMPLATE |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
class JSONPResponse(HttpResponse): |
|
12
|
|
|
def __init__(self, data, callback, encoder=DjangoJSONEncoder, safe=True, *args, **kwargs): |
|
13
|
|
|
if safe and not isinstance(data, dict): |
|
14
|
|
|
raise TypeError('In order to allow non-dict objects to be ' |
|
15
|
|
|
'serialized set the safe parameter to False') |
|
16
|
|
|
kwargs.setdefault('content_type', APPLICATION_JS) |
|
17
|
|
|
wrapped_payload = JSONP_TEMPLATE.format( |
|
18
|
|
|
callback=callback, |
|
19
|
|
|
# in case we got a string, for example when converting an HttpResponse instance |
|
20
|
|
|
payload=json.dumps(data, cls=encoder) if isinstance(data, dict) else data) |
|
21
|
|
|
super(JSONPResponse, self).__init__(content=wrapped_payload, **kwargs) |
|
22
|
|
|
|
|
23
|
|
|
@classmethod |
|
24
|
|
|
def from_http_response(cls, http_response, callback, *args, **kwargs): |
|
25
|
|
|
return cls(http_response.content, callback, safe=False, *args, **kwargs) |
|
26
|
|
|
|
|
27
|
|
|
|
|
28
|
|
|
def get_jsonp_response(data, callback=None): |
|
29
|
|
|
if not callback: |
|
30
|
|
|
return HttpResponseBadRequest('No callback supplied') |
|
31
|
|
|
if isinstance(data, dict): |
|
32
|
|
|
return JSONPResponse(data, callback) |
|
33
|
|
|
elif isinstance(data, HttpResponse): |
|
34
|
|
|
return JSONPResponse.from_http_response(data, callback) |
|
35
|
|
|
else: |
|
36
|
|
|
raise NotImplementedError('Not supported response type') |
|
37
|
|
|
|