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