author | Andrey Skvortsov <andrej.skvortzov@gmail.com> |
Fri, 15 Sep 2017 20:01:21 +0300 | |
changeset 1811 | 4e3c78a84c64 |
parent 1783 | 3311eea28d56 |
child 1850 | 614396cbffbf |
permissions | -rw-r--r-- |
371 | 1 |
# jsonrpc.py |
2 |
# original code: http://trac.pyworks.org/pyjamas/wiki/DjangoWithPyJamas |
|
3 |
# also from: http://www.pimentech.fr/technologies/outils |
|
1783
3311eea28d56
clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1769
diff
changeset
|
4 |
from datetime import date |
3311eea28d56
clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1769
diff
changeset
|
5 |
import datetime |
3311eea28d56
clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1769
diff
changeset
|
6 |
import sys |
3311eea28d56
clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1769
diff
changeset
|
7 |
|
371 | 8 |
from django.utils import simplejson |
9 |
from django.http import HttpResponse |
|
1783
3311eea28d56
clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1769
diff
changeset
|
10 |
from django import forms |
3311eea28d56
clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1769
diff
changeset
|
11 |
from django.core.serializers import serialize |
3311eea28d56
clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1769
diff
changeset
|
12 |
|
371 | 13 |
|
14 |
from pyjs.jsonrpc import JSONRPCServiceBase |
|
15 |
# JSONRPCService and jsonremote are used in combination to drastically |
|
16 |
# simplify the provision of JSONRPC services. use as follows: |
|
17 |
# |
|
18 |
# jsonservice = JSONRPCService() |
|
19 |
# |
|
20 |
# @jsonremote(jsonservice) |
|
21 |
# def test(request, echo_param): |
|
22 |
# return "echoing the param back: %s" % echo_param |
|
23 |
# |
|
24 |
# dump jsonservice into urlpatterns: |
|
25 |
# (r'^service1/$', 'djangoapp.views.jsonservice'), |
|
26 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
27 |
|
371 | 28 |
class JSONRPCService(JSONRPCServiceBase): |
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
29 |
|
371 | 30 |
def __call__(self, request, extra=None): |
31 |
return self.process(request.raw_post_data) |
|
32 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
33 |
|
371 | 34 |
def jsonremote(service): |
35 |
"""Make JSONRPCService a decorator so that you can write : |
|
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
36 |
|
371 | 37 |
from jsonrpc import JSONRPCService |
38 |
chatservice = JSONRPCService() |
|
39 |
||
40 |
@jsonremote(chatservice) |
|
41 |
def login(request, user_name): |
|
42 |
(...) |
|
43 |
""" |
|
44 |
def remotify(func): |
|
45 |
if isinstance(service, JSONRPCService): |
|
46 |
service.add_method(func.__name__, func) |
|
47 |
else: |
|
48 |
emsg = 'Service "%s" not found' % str(service.__name__) |
|
1765
ccf59c1f0b45
clean-up: fix PEP8 W602 deprecated form of raising exception
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1763
diff
changeset
|
49 |
raise NotImplementedError(emsg) |
371 | 50 |
return func |
51 |
return remotify |
|
52 |
||
53 |
||
54 |
# FormProcessor provides a mechanism for turning Django Forms into JSONRPC |
|
55 |
# Services. If you have an existing Django app which makes prevalent |
|
56 |
# use of Django Forms it will save you rewriting the app. |
|
57 |
# use as follows. in djangoapp/views.py : |
|
58 |
# |
|
59 |
# class SimpleForm(forms.Form): |
|
60 |
# testfield = forms.CharField(max_length=100) |
|
61 |
# |
|
62 |
# class SimpleForm2(forms.Form): |
|
63 |
# testfield = forms.CharField(max_length=20) |
|
64 |
# |
|
65 |
# processor = FormProcessor({'processsimpleform': SimpleForm, |
|
66 |
# 'processsimpleform2': SimpleForm2}) |
|
67 |
# |
|
68 |
# this will result in a JSONRPC service being created with two |
|
69 |
# RPC functions. dump "processor" into urlpatterns to make it |
|
70 |
# part of the app: |
|
71 |
# (r'^formsservice/$', 'djangoapp.views.processor'), |
|
72 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
73 |
|
371 | 74 |
def builderrors(form): |
75 |
d = {} |
|
76 |
for error in form.errors.keys(): |
|
77 |
if error not in d: |
|
78 |
d[error] = [] |
|
79 |
for errorval in form.errors[error]: |
|
80 |
d[error].append(unicode(errorval)) |
|
81 |
return d |
|
82 |
||
83 |
||
84 |
# contains the list of arguments in each field |
|
85 |
field_names = { |
|
86 |
'CharField': ['max_length', 'min_length'], |
|
87 |
'IntegerField': ['max_value', 'min_value'], |
|
88 |
'FloatField': ['max_value', 'min_value'], |
|
89 |
'DecimalField': ['max_value', 'min_value', 'max_digits', 'decimal_places'], |
|
90 |
'DateField': ['input_formats'], |
|
91 |
'DateTimeField': ['input_formats'], |
|
92 |
'TimeField': ['input_formats'], |
|
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
93 |
'RegexField': ['max_length', 'min_length'], # sadly we can't get the expr |
371 | 94 |
'EmailField': ['max_length', 'min_length'], |
95 |
'URLField': ['max_length', 'min_length', 'verify_exists', 'user_agent'], |
|
96 |
'ChoiceField': ['choices'], |
|
97 |
'FilePathField': ['path', 'match', 'recursive', 'choices'], |
|
98 |
'IPAddressField': ['max_length', 'min_length'], |
|
99 |
} |
|
100 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
101 |
|
371 | 102 |
def describe_field_errors(field): |
103 |
res = {} |
|
104 |
field_type = field.__class__.__name__ |
|
105 |
msgs = {} |
|
106 |
for n, m in field.error_messages.items(): |
|
107 |
msgs[n] = unicode(m) |
|
108 |
res['error_messages'] = msgs |
|
109 |
if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']: |
|
110 |
res['fields'] = map(describe_field, field.fields) |
|
111 |
return res |
|
112 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
113 |
|
371 | 114 |
def describe_fields_errors(fields, field_names): |
115 |
res = {} |
|
116 |
if not field_names: |
|
117 |
field_names = fields.keys() |
|
118 |
for name in field_names: |
|
119 |
field = fields[name] |
|
120 |
res[name] = describe_field_errors(field) |
|
121 |
return res |
|
122 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
123 |
|
371 | 124 |
def describe_field(field): |
125 |
res = {} |
|
126 |
field_type = field.__class__.__name__ |
|
1769
4665ba25a0ba
clean-up: fix PEP8 E125 continuation line with same indent as next logical line
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1767
diff
changeset
|
127 |
for fname in (field_names.get(field_type, []) + |
4665ba25a0ba
clean-up: fix PEP8 E125 continuation line with same indent as next logical line
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1767
diff
changeset
|
128 |
['help_text', 'label', 'initial', 'required']): |
371 | 129 |
res[fname] = getattr(field, fname) |
130 |
if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']: |
|
131 |
res['fields'] = map(describe_field, field.fields) |
|
132 |
return res |
|
133 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
134 |
|
371 | 135 |
def describe_fields(fields, field_names): |
136 |
res = {} |
|
137 |
if not field_names: |
|
138 |
field_names = fields.keys() |
|
139 |
for name in field_names: |
|
140 |
field = fields[name] |
|
141 |
res[name] = describe_field(field) |
|
142 |
return res |
|
143 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
144 |
|
371 | 145 |
class FormProcessor(JSONRPCService): |
146 |
def __init__(self, forms, _formcls=None): |
|
147 |
||
148 |
if _formcls is None: |
|
149 |
JSONRPCService.__init__(self) |
|
150 |
for k in forms.keys(): |
|
1754
63f4af6bf6d9
clean-up: fix most PEP8 E221 multiple spaces before operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1749
diff
changeset
|
151 |
s = FormProcessor({}, forms[k]) |
371 | 152 |
self.add_method(k, s.__process) |
153 |
else: |
|
154 |
JSONRPCService.__init__(self, forms) |
|
155 |
self.formcls = _formcls |
|
156 |
||
157 |
def __process(self, request, params, command=None): |
|
158 |
||
159 |
f = self.formcls(params) |
|
160 |
||
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
161 |
if command is None: # just validate |
371 | 162 |
if not f.is_valid(): |
1740
b789b695b5c6
clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1737
diff
changeset
|
163 |
return {'success': False, 'errors': builderrors(f)} |
b789b695b5c6
clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1737
diff
changeset
|
164 |
return {'success': True} |
371 | 165 |
|
1763
bcc07ff2362c
clean-up: fix PEP8 W601 .has_key() is deprecated, use 'in'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1754
diff
changeset
|
166 |
elif 'describe_errors' in command: |
371 | 167 |
field_names = command['describe_errors'] |
168 |
return describe_fields_errors(f.fields, field_names) |
|
169 |
||
1763
bcc07ff2362c
clean-up: fix PEP8 W601 .has_key() is deprecated, use 'in'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1754
diff
changeset
|
170 |
elif 'describe' in command: |
371 | 171 |
field_names = command['describe'] |
172 |
return describe_fields(f.fields, field_names) |
|
173 |
||
1763
bcc07ff2362c
clean-up: fix PEP8 W601 .has_key() is deprecated, use 'in'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1754
diff
changeset
|
174 |
elif 'save' in command: |
371 | 175 |
if not f.is_valid(): |
1740
b789b695b5c6
clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1737
diff
changeset
|
176 |
return {'success': False, 'errors': builderrors(f)} |
1737
a39c2918c015
clean-up: fix PEP8 E261 at least two spaces before inline comment
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
177 |
instance = f.save() # XXX: if you want more, over-ride save. |
1746
45d6f5fba016
clean-up: fix PEP8 E202 whitespace before ')'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1741
diff
changeset
|
178 |
return {'success': True, 'instance': json_convert(instance)} |
371 | 179 |
|
1763
bcc07ff2362c
clean-up: fix PEP8 W601 .has_key() is deprecated, use 'in'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1754
diff
changeset
|
180 |
elif 'html' in command: |
371 | 181 |
return {'success': True, 'html': f.as_table()} |
182 |
||
183 |
return "unrecognised command" |
|
184 |
||
185 |
# The following is incredibly convenient for saving vast amounts of |
|
186 |
# coding, avoiding doing silly things like this: |
|
187 |
# jsonresult = {'field1': djangoobject.field1, |
|
188 |
# 'field2': djangoobject.date.strftime('%Y.%M'), |
|
189 |
# ..... } |
|
190 |
# |
|
191 |
# The date/time flatten function is there because JSONRPC doesn't |
|
192 |
# support date/time objects or formats, so conversion to a string |
|
193 |
# is the most logical choice. pyjamas, being python, can easily |
|
194 |
# be used to parse the string result at the other end. |
|
195 |
# |
|
196 |
# use as follows: |
|
197 |
# |
|
198 |
# jsonservice = JSONRPCService() |
|
199 |
# |
|
200 |
# @jsonremote(jsonservice) |
|
201 |
# def list_some_model(request, start=0, count=10): |
|
202 |
# l = SomeDjangoModelClass.objects.filter() |
|
203 |
# res = json_convert(l[start:end]) |
|
204 |
# |
|
205 |
# @jsonremote(jsonservice) |
|
206 |
# def list_another_model(request, start=0, count=10): |
|
207 |
# l = AnotherDjangoModelClass.objects.filter() |
|
208 |
# res = json_convert(l[start:end]) |
|
209 |
# |
|
210 |
# dump jsonservice into urlpatterns to make the two RPC functions, |
|
211 |
# list_some_model and list_another_model part of the django app: |
|
212 |
# (r'^service1/$', 'djangoapp.views.jsonservice'), |
|
213 |
||
1749
d73b64672238
clean-up: fix PEP8 E305 expected 2 blank lines after class or function definition
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1746
diff
changeset
|
214 |
|
371 | 215 |
def dict_datetimeflatten(item): |
216 |
d = {} |
|
217 |
for k, v in item.items(): |
|
218 |
k = str(k) |
|
219 |
if isinstance(v, datetime.date): |
|
220 |
d[k] = str(v) |
|
221 |
elif isinstance(v, dict): |
|
222 |
d[k] = dict_datetimeflatten(v) |
|
223 |
else: |
|
224 |
d[k] = v |
|
225 |
return d |
|
226 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
227 |
|
371 | 228 |
def json_convert(l, fields=None): |
229 |
res = [] |
|
230 |
for item in serialize('python', l, fields=fields): |
|
231 |
res.append(dict_datetimeflatten(item)) |
|
232 |
return res |