forked from samuelclay/NewsBlur
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_functions.py
162 lines (145 loc) · 5.25 KB
/
json_functions.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
from django.db import models
from django.utils.functional import Promise
from django.utils.encoding import force_unicode
from django.utils import simplejson as json
from decimal import Decimal
from django.core import serializers
from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden, Http404
from django.core.mail import mail_admins
from django.db.models.query import QuerySet
from mongoengine.queryset import QuerySet as MongoQuerySet
from bson.objectid import ObjectId
import sys
import datetime
def decode(data):
if not data:
return data
return json.loads(data)
def encode(data, *args, **kwargs):
if type(data) == QuerySet: # Careful, ValuesQuerySet is a dict
# Django models
return serializers.serialize("json", data, *args, **kwargs)
else:
return json_encode(data, *args, **kwargs)
def json_encode(data, *args, **kwargs):
"""
The main issues with django's default json serializer is that properties that
had been added to an object dynamically are being ignored (and it also has
problems with some models).
"""
def _any(data):
ret = None
# Opps, we used to check if it is of type list, but that fails
# i.e. in the case of django.newforms.utils.ErrorList, which extends
# the type "list". Oh man, that was a dumb mistake!
if hasattr(data, 'to_json'):
ret = _any(data.to_json())
elif hasattr(data, 'canonical'):
ret = data.canonical()
elif isinstance(data, list):
ret = _list(data)
elif isinstance(data, set):
ret = _list(list(data))
# Same as for lists above.
elif isinstance(data, dict):
ret = _dict(data)
elif isinstance(data, (Decimal, ObjectId)):
# json.dumps() cant handle Decimal
ret = str(data)
elif isinstance(data, models.query.QuerySet):
# Actually its the same as a list ...
ret = _list(data)
elif isinstance(data, MongoQuerySet):
# Actually its the same as a list ...
ret = _list(data)
elif isinstance(data, models.Model):
ret = _model(data)
# here we need to encode the string as unicode (otherwise we get utf-16 in the json-response)
elif isinstance(data, basestring):
ret = unicode(data)
# see http://code.djangoproject.com/ticket/5868
elif isinstance(data, Promise):
ret = force_unicode(data)
elif isinstance(data, datetime.datetime) or isinstance(data, datetime.date):
ret = str(data)
else:
ret = data
return ret
def _model(data):
ret = {}
# If we only have a model, we only want to encode the fields.
for f in data._meta.fields:
ret[f.attname] = _any(getattr(data, f.attname))
# And additionally encode arbitrary properties that had been added.
fields = dir(data.__class__) + ret.keys()
add_ons = [k for k in dir(data) if k not in fields]
for k in add_ons:
ret[k] = _any(getattr(data, k))
return ret
def _list(data):
ret = []
for v in data:
ret.append(_any(v))
return ret
def _dict(data):
ret = {}
for k,v in data.items():
ret[str(k)] = _any(v)
return ret
if hasattr(data, 'to_json'):
data = data.to_json()
ret = _any(data)
return json.dumps(ret)
def json_view(func):
def wrap(request, *a, **kw):
response = func(request, *a, **kw)
return json_response(request, response)
if isinstance(func, HttpResponse):
return func
else:
return wrap
def json_response(request, response=None):
code = 200
if isinstance(response, HttpResponseForbidden):
return response
try:
if isinstance(response, dict):
response = dict(response)
if 'result' not in response:
response['result'] = 'ok'
authenticated = request.user.is_authenticated()
response['authenticated'] = authenticated
except KeyboardInterrupt:
# Allow keyboard interrupts through for debugging.
raise
except Http404:
raise Http404
except Exception, e:
# Mail the admins with the error
exc_info = sys.exc_info()
subject = 'JSON view error: %s' % request.path
try:
request_repr = repr(request)
except:
request_repr = 'Request repr() unavailable'
import traceback
message = 'Traceback:\n%s\n\nRequest:\n%s' % (
'\n'.join(traceback.format_exception(*exc_info)),
request_repr,
)
response = {'result': 'error',
'text': unicode(e)}
code = 500
if not settings.DEBUG:
mail_admins(subject, message, fail_silently=True)
else:
print '\n'.join(traceback.format_exception(*exc_info))
json = json_encode(response)
return HttpResponse(json, mimetype='application/json', status=code)
def main():
test = {1: True, 2: u"string", 3: 30}
json_test = json_encode(test)
print test, json_test
if __name__ == '__main__':
main()