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