forked from makinacorpus/django-ode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmixins.py
80 lines (64 loc) · 2.48 KB
/
mixins.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
#from django.utils.encoding import force_unicode
from django.utils.encoding import force_text
from django.utils.functional import Promise
from django.utils.translation import ugettext as _
from django.utils.cache import add_never_cache_headers
from django.views.generic.base import TemplateView
import logging
logger = logging.getLogger(__name__)
class LazyEncoder(DjangoJSONEncoder):
"""Encodes django's lazy i18n strings
"""
def default(self, obj):
if isinstance(obj, Promise):
#return force_unicode(obj)
return force_text(obj)
return super(LazyEncoder, self).default(obj)
class JSONResponseMixin(object):
is_clean = False
def render_to_response(self, context):
""" Returns a JSON response containing 'context' as payload
"""
return self.get_json_response(context)
def get_json_response(self, content, **httpresponse_kwargs):
""" Construct an `HttpResponse` object.
"""
response = HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
add_never_cache_headers(response)
return response
def post(self, *args, **kwargs):
return self.get(*args, **kwargs)
def get(self, request, *args, **kwargs):
self.request = request
response = None
try:
func_val = self.get_context_data(**kwargs)
if not self.is_clean:
assert isinstance(func_val, dict)
response = dict(func_val)
if 'result' not in response:
response['result'] = 'ok'
else:
response = func_val
except KeyboardInterrupt:
# Allow keyboard interrupts through for debugging.
raise
except Exception as e:
logger.error('JSON view error: %s' % request.path, exc_info=True)
# Come what may, we're returning JSON.
if hasattr(e, 'message'):
msg = e.message
msg += repr(e)
else:
msg = _('Internal error') + ': ' + str(e)
response = {'result': 'error',
'text': msg}
dump = json.dumps(response, cls=LazyEncoder)
return self.render_to_response(dump)
class JSONResponseView(JSONResponseMixin, TemplateView):
pass