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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# coding: utf8
# Copyright (c) 2013, Cyril MORISSE ( @cmorisse )
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# TODO: Add a shortcut to ir.model.data.get_object_reference('module', identifier')
# TODO: Add a complete example of OpenERP configuration with wizard and settings to enable exec_workflow test
# TODO: By default, reinject in every call, the context got by authenticate
# TODO: coverage ?
# TODO: publish on pypi
import requests
import json
class OpenERPJSONRPCClientMethodNotFoundError(BaseException):
pass
class OpenERPJSONRPCClientServiceNotFoundError(BaseException):
pass
class OpenERPJSONRPCClientException(BaseException):
"""
Raised when jsonrpc() returns an error response
"""
def __init__(self, code, message, data, json_response):
self.code = code
self.message = message
self.data = data
self.json_response = json_response
class OpenERPServiceProxy(object):
"""
A proxy to a generic OpenERP Service (eg. db).
"""
def __init__(self, json_rpc_client, service_name):
self._json_rpc_client = json_rpc_client
self.service_name = service_name
def __getattr__(self, method):
"""
Returns a wrapper method ready for OpenERPJSONRPCClient calls.
"""
def proxy(*args, **kwargs):
return self._json_rpc_client.call(self.service_name, method, *args, **kwargs)
return proxy
class OpenERPModelProxy(object):
"""
A proxy to a dataset model which allow to call methods on models using call_kw.
"""
def __init__(self, json_rpc_client, model_name):
self._json_rpc_client = json_rpc_client
self.model_name = model_name
def __getattr__(self, method):
"""
On a model, method are called using call_kw
Returns a wrapper method ready for a call to dataset.call_kw()
"""
def proxy(*args, **kwargs):
return self._json_rpc_client.dataset_call_kw(self.model_name, method, *args, **kwargs)
return proxy
class OpenERPJSONRPCClient():
first_connection = None
# List of OpenERP v7.0 Available Services
# can be found in openerp/addons/web/controllers/main.py
OE_SERVICES = (
'webclient', 'proxy', 'session', 'database',
'menu', 'dataset', 'view', 'treeview', 'binary',
'action', 'export', 'export/csv', 'export/xls',
'report',
)
def __init__(self, base_url):
self._rid = 0 # a unique request id incremented at each request
self._base_url = base_url
self._cookies = dict()
self._session_id = None
self.user_context = None
# We call get_session_info() to retreive a werkzeug cookie
# and an OpenERP session_id
first_connection = self.jsonrpc(self._url_for_method('session', 'get_session_info'),
'call',
session_id=None,
context={})
if first_connection.cookies.get('sid', False):
self._cookies = dict(sid=first_connection.cookies['sid'])
# self._session_id = first_connection.json()['result']['session_id']
self.first_connection = first_connection
def getFC(self):
return self.first_connection
def _url_for_method(self, service_name, method_name):
return self._base_url + '/web/' + service_name + '/' + method_name
def jsonrpc(self, url, method, *args, **kwargs):
"""
Executes a "standard" JSON-RPC calls
:param url: url of the end point to call
:param method: JSONRPC method to call
:param args: positional args if any
:param kwargs: keyword args if any
:return: result of the call
"""
# JSONRPC do not allow to mix positional and keyword arguments
# If args are defined we use them, else we try with keywords args then fallback to None
params = args or kwargs
post_data = {
'json-rpc': "2.0",
'method': method,
'params': params,
'id': self._rid,
}
server_response = requests.post(url, json.dumps(post_data), cookies=self._cookies)
self._rid += 1
return server_response
def oe_jsonrpc(self, url, method, params={}):
"""
Executes an OpenERP flavored JSON-RPC calls :
- pass OpenERP _session_id along each request
- return the result key of the Call Response dict or raise an Exception
:param url: OpenERP Service/request/ to call (cf. openerp/addons/web/controllers/main.py)
:type url: str
:param method: JSON-RPC method name. with OE it's always call or call_kw
:type method: str
:param params: content of the JSON-RPC params dict. Must be a dict !
:type params: dict
:return: result of the call
:rtype: dict
"""
post_data = {
'json-rpc': "2.0",
'method': method,
'params': params,
'id': self._rid,
}
self._rid += 1
# We pass OpenERP _session_id at each request
if self._session_id:
post_data['params']['session_id'] = self._session_id
server_response = requests.post(url, json.dumps(post_data), cookies=self._cookies)
if server_response.status_code != 200:
raise OpenERPJSONRPCClientMethodNotFoundError("%s is not a valid URL." % url)
json_response = server_response.json()
try:
return json_response['result']
except KeyError:
pass
# JSON-RPC returns an error. So we raise an OpenERPJSONRPCClientException
# based on the (error) response content.
raise OpenERPJSONRPCClientException(json_response['error']['code'],
json_response['error']['message'],
json_response['error']['data'], json_response)
def call_with_named_arguments(self, service, method, *args, **kwargs):
"""
use JSON-RPC named arguments style.
each named arg is mapped to a key in the param dict()
eg. authenticate(db='db_name', login='admin', password='admin', base_location='http://localhost:8069')
is called with:
{
"jsonrpc":"2.0",
"method":"call",
"params": {
"db": "db_name",
"login": "admin",
"password":"admin",
"base_location":"http://localhost:8069",
"session_id":"6fd6928ec15a48ea9a604e1d44238788",
"context":{}
},
"id":"r6"
}
Returns jsonrpc.result as a dict
or return the whole json response in case of error
"""
#: :type: requests.Response
url = self._url_for_method(service, method)
params = kwargs
response = self.oe_jsonrpc(url, "call", params)
return response
def call_with_fields_arguments(self, service, method, *args, **kwargs):
"""
use JSON-RPC named arguments style but all OpenERP args are stored in a dict under a "fields" named parameter
eg. authenticate(db='db_name', login='admin', password='admin', base_location='http://localhost:8069')
is called with:
{
"jsonrpc":"2.0",
"method":"call",
"params": {
'fields': {
"db": "db_name",
"login": "admin",
"password":"admin",
"base_location":"http://localhost:8069",
},
"session_id":"6fd6928ec15a48ea9a604e1d44238788",
"context":{}
},
"id":"r6"
}
Returns jsonrpc.result as a dict
or return the whole json response in case of error
"""
#: :type: requests.Response
url = self._url_for_method(service, method)
# we extract context which must not be encoded as a "field" and remain a param
context = kwargs['context']
del kwargs['context']
# let's add all kwargs as fields items
params = {'fields': [{'name': k, 'value': v} for (k, v) in kwargs.items()]}
# we re-inject context at the same level as "fields"
params['context'] = context
response = self.oe_jsonrpc(url, "call", params)
return response
@property
def get_available_services(self):
return OpenERPJSONRPCClient.OE_SERVICES
def get_service(self, service_name):
if service_name in OpenERPJSONRPCClient.OE_SERVICES:
return OpenERPServiceProxy(self, service_name)
raise OpenERPJSONRPCClientServiceNotFoundError()
def get_model(self, model_name):
"""OpenERP self.pool.get(...) equivalent"""
return OpenERPModelProxy(self, model_name)
#
# database service
#
def db_get_list(self, context={}):
"""
:return: list of database on server (beware of any filter in server config)
:rtype: list
"""
return self.call_with_named_arguments('database', 'get_list', context=context)
def db_create(self, super_admin_pwd, database_name, demo_data, language, user_admin_password, context={}):
"""
Create a new database
:param super_admin_pwd: OpenERP admin password.
:type super_admin_pwd: str
:param database_name: Name of the database to create?
:type database_name: str
:param demo_data: Shall we load "demo" data in the crated database ?"
:type demo_data: bool
:param language: "Translation to load (eg. Fr_fr)
:type language: str
:param user_admin_password: Password of the admin user of the created database
:type user_admin_password: str
:return:
:rtype:
"""
return self.call_with_fields_arguments('database', 'create',
super_admin_pwd=super_admin_pwd,
db_name=database_name,
demo_data=demo_data,
db_lang=language,
create_admin_pwd=user_admin_password,
context=context)
def db_duplicate(self, super_admin_pwd, source_database_name, duplicated_database_name, context={}):
"""
Create a new database
:param super_admin_pwd: OpenERP admin password.
:type super_admin_pwd: str
:param source_database_name: Name of the database use as duplication source
:type source_database_name: str
:param duplicated_database_name: Name of the duplicated (destination) database
:type duplicated_database_name: str
:return:
:rtype:
"""
return self.call_with_fields_arguments('database', 'duplicate',
super_admin_pwd=super_admin_pwd,
db_original_name=source_database_name,
db_name=duplicated_database_name,
context=context)
def db_drop(self, super_admin_pwd, database_name, context={}):
"""
Create a new database
:param super_admin_pwd: OpenERP admin password.
:type super_admin_pwd: str
:param database_name: Name of the database to drop
:type database_name: str
:return:
:rtype:
"""
return self.call_with_fields_arguments('database', 'drop',
drop_pwd=super_admin_pwd,
drop_db=database_name,
context=context)
def db_change_password(self, old_pwd, new_pwd, context={}):
"""
Change OpenERP admin password
:param old_pwd: Current OpenERP admin password.
:type old_pwd: str
:param new_pwd: New OpenERP admin password to let
:type new_pwd: str
:return:
:rtype:
"""
return self.call_with_fields_arguments('database', 'change_password',
old_pwd=old_pwd,
new_pwd=new_pwd,
context=context)
#
# Session service
#
def session_get_info(self, context={}):
"""
Retreive session information
:return: a dict containing session information
"""
return self.call_with_named_arguments('session', 'get_session_info', context=context)
def session_authenticate(self, db, login, password, base_location=None, context={}):
"""
Authenticate against a database.
:param db:
:param login:
:param password:
:param base_location:
:return:
"""
result = self.call_with_named_arguments('session',
'authenticate',
db=db,
login=login,
password=password,
base_location=base_location,
context=context)
self.user_context = result.get('user_context', {})
return result
def session_sc_list(self, context={}):
"""
Retreive session information
:return: a dict containing session information
"""
return self.call_with_named_arguments('session', 'sc_list', context=context)
#
# Dataset service
#
def dataset_search_read(self, model, fields=False, offset=0, limit=False, domain=[], sort=None, context={}):
"""
Perform a serch and a read in the same roundtrip
:param model: Model involved in search
:param fields: Fields you want to fetch. All by default
:param offset: Offset of the first record you want to fetch. 0 by default
:param limit: Number of record you want to fetch. All by default
:param domain: An OpenERP domain specifying search_criteria. All records by default (OpenERP expects an empty domain( [] ) in that case)
:param sort: Columns to sort record by. osv.Model _order attribute by default
:return:
"""
return self.call_with_named_arguments('dataset', 'search_read',
model=model,
fields=fields,
offset=offset,
limit=limit,
domain=domain,
sort=sort,
context=context)
def dataset_load(self, model, id, fields=False, context={}):
"""
Load all fields of one object identified by a model and an id
:param model: Model to load
:param id: identifier of the object to load (only one)
:param fields: Exists but unused in the controller definition
:return: a dict with one key named "value" containing a dict of all object fields
"""
return self.call_with_named_arguments('dataset', 'load',
model=model,
id=id,
fields=fields,
context=context)
def dataset_call_kw(self, model, method, *args, **kwargs):
"""
Packs args and kwargs so that they are compatible with dataset/call_kw json request
then invoke dataset/call_kw
We pack arguments so that they conform to this structure:
{
"id": "r78",
"jsonrpc": "2.0",
"method": "call",
"params": {
"method": "create",
"model": "res.users",
"args": [
{
"action_id": false,
"active": true,
"company_id": 1,
"company_ids": [
[
6,
false,
[
1
]
]
],
...
}
],
"kwargs": {
"context": {
"lang": "Fr_fr",
"tz": false,
"uid": 1
}
},
"context": {
"lang": "Fr_fr",
"tz": false,
"uid": 1
},
"session_id": "d3b252a5526646b0b3073d4114d86bda"
}
}
This method is used by OpenERPModelProxy
"""
url = self._url_for_method('dataset', 'call_kw')
# we build params
params = {
'method': method,
'model': model,
'args': args,
'kwargs': kwargs,
# if there is a context in kw_args, we duplicate it at "params" level
'context': kwargs.get('context', {})
}
response = self.oe_jsonrpc(url, "call", params)
return response
def dataset_exec_workflow(self, model, id, signal):
"""Trigger signal on object id of model
:return: workflow execution result
"""
return self.call_with_named_arguments('dataset', 'exec_workflow',
model=model,
id=id,
signal=signal)
# Note: We don't implement exec_button() as it modifies returned action values in a way which is not consistent
# with server side behavior