Debian Codegraph @

odoorpc/odoo.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright 2014 Sébastien Alix
3 # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl)
4 """This module contains the ``ODOO`` class which is the entry point to manage
5 an `Odoo` server.
6 """
7 from odoorpc import error, rpc, session, tools
8 from odoorpc.db import DB
9 from odoorpc.env import Environment
10 from odoorpc.report import Report
11
12
13 class ODOO(object):
14 """Return a new instance of the :class:`ODOO` class.
15 `JSON-RPC` protocol is used to make requests, and the respective values
16 for the `protocol` parameter are ``jsonrpc`` (default) and ``jsonrpc+ssl``.
17
18 .. doctest::
19 :options: +SKIP
20
21 >>> import odoorpc
22 >>> odoo = odoorpc.ODOO('localhost', protocol='jsonrpc', port=8069)
23
24 `OdooRPC` will try by default to detect the server version in order to
25 adapt its requests if necessary. However, it is possible to force the
26 version to use with the `version` parameter:
27
28 .. doctest::
29 :options: +SKIP
30
31 >>> odoo = odoorpc.ODOO('localhost', version='12.0')
32
33 You can also define a custom URL opener to handle HTTP requests. A use
34 case is to manage a basic HTTP authentication in front of `Odoo`:
35
36 .. doctest::
37 :options: +SKIP
38
39 >>> import urllib.request
40 >>> import odoorpc
41 >>> pwd_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
42 >>> pwd_mgr.add_password(None, "http://example.net", "userName", "passWord")
43 >>> auth_handler = urllib.request.HTTPBasicAuthHandler(pwd_mgr)
44 >>> opener = urllib.request.build_opener(auth_handler)
45 >>> odoo = odoorpc.ODOO('example.net', port=80, opener=opener)
46
47 *Python 2:*
48
49 :raise: :class:`odoorpc.error.InternalError`
50 :raise: `ValueError` (wrong protocol, port value, timeout value)
51 :raise: `urllib2.URLError` (connection error)
52
53 *Python 3:*
54
55 :raise: :class:`odoorpc.error.InternalError`
56 :raise: `ValueError` (wrong protocol, port value, timeout value)
57 :raise: `urllib.error.URLError` (connection error)
58 """
59
60 def __init__(
61 self,
62 host='localhost',
63 protocol='jsonrpc',
64 port=8069,
65 timeout=120,
66 version=None,
67 opener=None,
68 ):
69 if protocol not in ['jsonrpc', 'jsonrpc+ssl']:
70 txt = (
71 "The protocol '{0}' is not supported by the ODOO class. "
72 "Please choose a protocol among these ones: {1}"
73 )
74 txt = txt.format(protocol, ['jsonrpc', 'jsonrpc+ssl'])
75 raise ValueError(txt)
76 try:
77 port = int(port)
78 except (ValueError, TypeError):
79 raise ValueError("The port must be an integer")
80 try:
81 if timeout is not None:
82 timeout = float(timeout)
83 except (ValueError, TypeError):
84 raise ValueError("The timeout must be a float")
85 self._host = host
86 self._port = port
87 self._protocol = protocol
88 self._env = None
89 self._login = None
90 self._password = None
91 self._db = DB(self)
92 self._report = Report(self)
93 # Instanciate the server connector
94 try:
95 self._connector = rpc.PROTOCOLS[protocol](
96 self._host, self._port, timeout, version, opener=opener
97 )
98 except rpc.error.ConnectorError as exc:
99 raise error.InternalError(exc.message)
100 # Dictionary of configuration options
101 self._config = tools.Config(
102 self,
103 {'auto_commit': True, 'auto_context': True, 'timeout': timeout},
104 )
105
106 @property
107 def config(self):
108 """Dictionary of available configuration options.
109
110 .. doctest::
111 :options: +SKIP
112
113 >>> odoo.config
114 {'auto_commit': True, 'auto_context': True, 'timeout': 120}
115
116 .. doctest::
117 :hide:
118
119 >>> 'auto_commit' in odoo.config
120 True
121 >>> 'auto_context' in odoo.config
122 True
123 >>> 'timeout' in odoo.config
124 True
125
126 - ``auto_commit``: if set to `True` (default), each time a value is set
127 on a record field a RPC request is sent to the server to update the
128 record (see :func:`odoorpc.env.Environment.commit`).
129
130 - ``auto_context``: if set to `True` (default), the user context will
131 be sent automatically to every call of a
132 :class:`model <odoorpc.models.Model>` method (default: `True`):
133
134 .. doctest::
135 :options: +SKIP
136
137 >>> odoo.env.context['lang'] = 'fr_FR'
138 >>> Product = odoo.env['product.product']
139 >>> Product.name_get([2]) # Context sent by default ('lang': 'fr_FR' here)
140 [[2, 'Surveillance sur site']]
141 >>> odoo.config['auto_context'] = False
142 >>> Product.name_get([2]) # No context sent, 'en_US' used
143 [[2, 'On Site Monitoring']]
144
145 - ``timeout``: set the maximum timeout in seconds for a RPC request
146 (default: `120`):
147
148 >>> odoo.config['timeout'] = 300
149
150 """
151 return self._config
152
153 @property
154 def version(self):
155 """The version of the server.
156
157 .. doctest::
158 :options: +SKIP
159
160 >>> odoo.version
161 '12.0'
162 """
163 return self._connector.version
164
165 @property
166 def db(self):
167 """The database management service.
168 See the :class:`odoorpc.db.DB` class.
169 """
170 return self._db
171
172 @property
173 def report(self):
174 """The report management service.
175 See the :class:`odoorpc.report.Report` class.
176 """
177 return self._report
178
179 host = property(
180 lambda self: self._host,
181 doc="Hostname of IP address of the the server.",
182 )
183 port = property(lambda self: self._port, doc="The port used.")
184 protocol = property(lambda self: self._protocol, doc="The protocol used.")
185
186 @property
187 def env(self):
188 """The environment which wraps data to manage records such as the
189 user context and the registry to access data model proxies.
190
191 >>> Partner = odoo.env['res.partner']
192 >>> Partner
193 Model('res.partner')
194
195 See the :class:`odoorpc.env.Environment` class.
196 """
197 self._check_logged_user()
198 return self._env
199
200 def json(self, url, params):
201 """Low level method to execute JSON queries.
202 It basically performs a request and raises an
203 :class:`odoorpc.error.RPCError` exception if the response contains
204 an error.
205
206 You have to know the names of each parameter required by the function
207 called, and set them in the `params` dictionary.
208
209 Here an authentication request:
210
211 .. doctest::
212 :options: +SKIP
213
214 >>> data = odoo.json(
215 ... '/web/session/authenticate',
216 ... {'db': 'db_name', 'login': 'admin', 'password': 'admin'})
217 >>> from pprint import pprint
218 >>> pprint(data)
219 {'id': 645674382,
220 'jsonrpc': '2.0',
221 'result': {'db': 'db_name',
222 'session_id': 'fa740abcb91784b8f4750c5c5b14da3fcc782d11',
223 'uid': 1,
224 'user_context': {'lang': 'en_US',
225 'tz': 'Europe/Brussels',
226 'uid': 1},
227 'username': 'admin'}}
228
229 .. doctest::
230 :hide:
231
232 >>> data = odoo.json(
233 ... '/web/session/authenticate',
234 ... {'db': DB, 'login': USER, 'password': PWD})
235 >>> data['result']['db'] == DB
236 True
237 >>> data['result']['uid'] in [1, 2]
238 True
239 >>> data['result']['username'] == USER
240 True
241
242 And a call to the ``read`` method of the ``res.users`` model:
243
244 .. doctest::
245 :options: +SKIP
246
247 >>> data = odoo.json(
248 ... '/web/dataset/call',
249 ... {'model': 'res.users', 'method': 'read',
250 ... 'args': [[2], ['name']]})
251 >>> from pprint import pprint
252 >>> pprint(data)
253 {'id': ...,
254 'jsonrpc': '2.0',
255 'result': [{'id': 2, 'name': 'Mitchell Admin'}]}
256
257 *Python 2:*
258
259 :return: a dictionary (JSON response)
260 :raise: :class:`odoorpc.error.RPCError`
261 :raise: `urllib2.HTTPError` (if `params` is not a dictionary)
262 :raise: `urllib2.URLError` (connection error)
263
264 *Python 3:*
265
266 :return: a dictionary (JSON response)
267 :raise: :class:`odoorpc.error.RPCError`
268 :raise: `urllib.error.HTTPError` (if `params` is not a dictionary)
269 :raise: `urllib.error.URLError` (connection error)
270 """
271 data = self._connector.proxy_json(url, params)
272 if data.get('error'):
273 raise error.RPCError(
274 data['error']['data']['message'], data['error']
275 )
276 return data
277
278 def http(self, url, data=None, headers=None):
279 """Low level method to execute raw HTTP queries.
280
281 .. note::
282
283 For low level JSON-RPC queries, see the more convenient
284 :func:`odoorpc.ODOO.json` method instead.
285
286 You have to know the names of each POST parameter required by the
287 URL, and set them in the `data` string/buffer.
288 The `data` argument must be built by yourself, following the expected
289 URL parameters (with :func:`urllib.urlencode` function for simple
290 parameters, or multipart/form-data structure to handle file upload).
291
292 E.g., the HTTP raw query to get the company logo on `Odoo 12.0`:
293
294 .. doctest::
295
296 >>> response = odoo.http('web/binary/company_logo')
297 >>> binary_data = response.read()
298
299 *Python 2:*
300
301 :return: `urllib.addinfourl`
302 :raise: `urllib2.HTTPError`
303 :raise: `urllib2.URLError` (connection error)
304
305 *Python 3:*
306
307 :return: `http.client.HTTPResponse`
308 :raise: `urllib.error.HTTPError`
309 :raise: `urllib.error.URLError` (connection error)
310 """
311 return self._connector.proxy_http(url, data, headers)
312
313 # NOTE: in the past this function was implemented as a decorator for
314 # methods needing to be checked, but Sphinx documentation generator is not
315 # able to parse decorated methods.
316 def _check_logged_user(self):
317 """Check if a user is logged. Otherwise, an error is raised."""
318 if not self._env or not self._password or not self._login:
319 raise error.InternalError("Login required")
320
321 def login(self, db, login='admin', password='admin'):
322 """Log in as the given `user` with the password `passwd` on the
323 database `db`.
324
325 .. doctest::
326 :options: +SKIP
327
328 >>> odoo.login('db_name', 'admin', 'admin')
329 >>> odoo.env.user.name
330 'Administrator'
331
332 *Python 2:*
333
334 :raise: :class:`odoorpc.error.RPCError`
335 :raise: `urllib2.URLError` (connection error)
336
337 *Python 3:*
338
339 :raise: :class:`odoorpc.error.RPCError`
340 :raise: `urllib.error.URLError` (connection error)
341 """
342 # Get the user's ID and generate the corresponding user record
343 if tools.v(self.version)[0] >= 10:
344 data = self.json(
345 "/jsonrpc",
346 params={
347 "service": "common",
348 "method": "login",
349 "args": [db, login, password],
350 },
351 )
352 uid = data["result"]
353 else:
354 # Needed to get 'report' service working on Odoo < 10.0
355 data = self.json(
356 "/web/session/authenticate",
357 {"db": db, "login": login, "password": password},
358 )
359 uid = data["result"]["uid"]
360 if uid:
361 if tools.v(self.version)[0] >= 10:
362 args_to_send = [db, uid, password, "res.users", "context_get"]
363 context = self.json(
364 "/jsonrpc",
365 {
366 "service": "object",
367 "method": "execute",
368 "args": args_to_send,
369 },
370 )["result"]
371 context["uid"] = uid
372 else:
373 context = data["result"]["user_context"]
374 self._env = Environment(self, db, uid, context=context)
375 self._login = login
376 self._password = password
377 else:
378 raise error.RPCError("Wrong login ID or password")
379
380 def logout(self):
381 """Log out the user.
382
383 >>> odoo.logout()
384 True
385
386 *Python 2:*
387
388 :return: `True` if the operation succeed, `False` if no user was logged
389 :raise: :class:`odoorpc.error.RPCError`
390 :raise: `urllib2.URLError` (connection error)
391
392 *Python 3:*
393
394 :return: `True` if the operation succeed, `False` if no user was logged
395 :raise: :class:`odoorpc.error.RPCError`
396 :raise: `urllib.error.URLError` (connection error)
397 """
398 if not self._env:
399 return False
400 if tools.v(self.version)[0] < 10:
401 self.json('/web/session/destroy', {})
402 self._env = None
403 self._login = None
404 self._password = None
405 return True
406
407 def close(self):
408 """Same than :attr:`odoorpc.ODOO.logout` method.
409
410 Here for the compatibility with `contextlib.closing`:
411
412 .. doctest::
413 :options: +SKIP
414
415 >>> import contextlib
416 >>> odoo.login('db_name', 'admin', 'admin')
417 >>> with contextlib.closing(odoo):
418 ... print(odoo.env.user.name)
419 ...
420 Mitchell Admin
421 """
422 return self.logout()
423
424 # ------------------------- #
425 # -- Raw XML-RPC methods -- #
426 # ------------------------- #
427
428 def execute(self, model, method, *args):
429 """Execute the `method` of `model`.
430 `*args` parameters varies according to the `method` used.
431
432 .. doctest::
433 :options: +SKIP
434
435 >>> odoo.execute('res.partner', 'read', [1], ['name'])
436 [{'id': 1, 'name': 'YourCompany'}]
437
438 .. doctest::
439 :hide:
440
441 >>> data = odoo.execute('res.partner', 'read', [1], ['name'])
442 >>> data[0]['id'] == 1
443 True
444 >>> data[0]['name'] == 'YourCompany'
445 True
446
447 *Python 2:*
448
449 :return: the result returned by the `method` called
450 :raise: :class:`odoorpc.error.RPCError`
451 :raise: :class:`odoorpc.error.InternalError` (if not logged)
452 :raise: `urllib2.URLError` (connection error)
453
454 *Python 3:*
455
456 :return: the result returned by the `method` called
457 :raise: :class:`odoorpc.error.RPCError`
458 :raise: :class:`odoorpc.error.InternalError` (if not logged)
459 :raise: `urllib.error.URLError` (connection error)
460 """
461 self._check_logged_user()
462 # Execute the query
463 args_to_send = [
464 self.env.db,
465 self.env.uid,
466 self._password,
467 model,
468 method,
469 ]
470 args_to_send.extend(args)
471 data = self.json(
472 '/jsonrpc',
473 {'service': 'object', 'method': 'execute', 'args': args_to_send},
474 )
475 return data.get('result')
476
477 def execute_kw(self, model, method, args=None, kwargs=None):
478 """Execute the `method` of `model`.
479 `args` is a list of parameters (in the right order),
480 and `kwargs` a dictionary (named parameters). Both varies according
481 to the `method` used.
482
483 .. doctest::
484 :options: +SKIP
485
486 >>> odoo.execute_kw('res.partner', 'read', [[1]], {'fields': ['name']})
487 [{'id': 1, 'name': 'YourCompany'}]
488
489 .. doctest::
490 :hide:
491
492 >>> data = odoo.execute_kw('res.partner', 'read', [[1]], {'fields': ['name']})
493 >>> data[0]['id'] == 1
494 True
495 >>> data[0]['name'] == 'YourCompany'
496 True
497
498 *Python 2:*
499
500 :return: the result returned by the `method` called
501 :raise: :class:`odoorpc.error.RPCError`
502 :raise: :class:`odoorpc.error.InternalError` (if not logged)
503 :raise: `urllib2.URLError` (connection error)
504
505 *Python 3:*
506
507 :return: the result returned by the `method` called
508 :raise: :class:`odoorpc.error.RPCError`
509 :raise: :class:`odoorpc.error.InternalError` (if not logged)
510 :raise: `urllib.error.URLError` (connection error)
511 """
512 self._check_logged_user()
513 # Execute the query
514 args = args or []
515 kwargs = kwargs or {}
516 args_to_send = [
517 self.env.db,
518 self.env.uid,
519 self._password,
520 model,
521 method,
522 ]
523 args_to_send.extend([args, kwargs])
524 data = self.json(
525 '/jsonrpc',
526 {
527 'service': 'object',
528 'method': 'execute_kw',
529 'args': args_to_send,
530 },
531 )
532 return data.get('result')
533
534 def exec_workflow(self, model, record_id, signal):
535 """Execute the workflow `signal` on
536 the instance having the ID `record_id` of `model`.
537
538 *Python 2:*
539
540 :raise: :class:`odoorpc.error.RPCError`
541 :raise: :class:`odoorpc.error.InternalError` (if not logged)
542 :raise: `urllib2.URLError` (connection error)
543
544 *Python 3:*
545
546 :raise: :class:`odoorpc.error.RPCError`
547 :raise: :class:`odoorpc.error.InternalError` (if not logged)
548 :raise: `urllib.error.URLError` (connection error)
549 """
550 if tools.v(self.version)[0] >= 11:
551 raise DeprecationWarning(
552 u"Workflows have been removed in Odoo >= 11.0"
553 )
554 self._check_logged_user()
555 # Execute the workflow query
556 args_to_send = [
557 self.env.db,
558 self.env.uid,
559 self._password,
560 model,
561 signal,
562 record_id,
563 ]
564 data = self.json(
565 '/jsonrpc',
566 {
567 'service': 'object',
568 'method': 'exec_workflow',
569 'args': args_to_send,
570 },
571 )
572 return data.get('result')
573
574 # ---------------------- #
575 # -- Session methods -- #
576 # ---------------------- #
577
578 def save(self, name, rc_file='~/.odoorpcrc'):
579 """Save the current :class:`ODOO <odoorpc.ODOO>` instance (a `session`)
580 inside `rc_file` (``~/.odoorpcrc`` by default). This session will be
581 identified by `name`::
582
583 >>> import odoorpc
584 >>> odoo = odoorpc.ODOO('localhost', port=8069)
585 >>> odoo.login('db_name', 'admin', 'admin')
586 >>> odoo.save('foo')
587
588 Use the :func:`list <odoorpc.ODOO.list>` class method to list all
589 stored sessions, and the :func:`load <odoorpc.ODOO.load>` class method
590 to retrieve an already-connected :class:`ODOO <odoorpc.ODOO>` instance.
591
592 *Python 2:*
593
594 :raise: :class:`odoorpc.error.InternalError` (if not logged)
595 :raise: `IOError`
596
597 *Python 3:*
598
599 :raise: :class:`odoorpc.error.InternalError` (if not logged)
600 :raise: `PermissionError`
601 :raise: `FileNotFoundError`
602 """
603 self._check_logged_user()
604 data = {
605 'type': self.__class__.__name__,
606 'host': self.host,
607 'protocol': self.protocol,
608 'port': self.port,
609 'timeout': self.config['timeout'],
610 'user': self._login,
611 'passwd': self._password,
612 'database': self.env.db,
613 }
614 session.save(name, data, rc_file)
615
616 @classmethod
617 def load(cls, name, rc_file='~/.odoorpcrc'):
618 """Return a connected :class:`ODOO` session identified by `name`:
619
620 .. doctest::
621 :options: +SKIP
622
623 >>> import odoorpc
624 >>> odoo = odoorpc.ODOO.load('foo')
625
626 Such sessions are stored with the
627 :func:`save <odoorpc.ODOO.save>` method.
628
629 *Python 2:*
630
631 :raise: :class:`odoorpc.error.RPCError`
632 :raise: `urllib2.URLError` (connection error)
633
634 *Python 3:*
635
636 :raise: :class:`odoorpc.error.RPCError`
637 :raise: `urllib.error.URLError` (connection error)
638 """
639 data = session.get(name, rc_file)
640 if data.get('type') != cls.__name__:
641 raise error.InternalError(
642 "'{}' session is not of type '{}'".format(name, cls.__name__)
643 )
644 odoo = cls(
645 host=data['host'],
646 protocol=data['protocol'],
647 port=data['port'],
648 timeout=data['timeout'],
649 )
650 odoo.login(
651 db=data['database'], login=data['user'], password=data['passwd']
652 )
653 return odoo
654
655 @classmethod
656 def list(cls, rc_file='~/.odoorpcrc'):
657 """Return a list of all stored sessions available in the
658 `rc_file` file:
659
660 .. doctest::
661 :options: +SKIP
662
663 >>> import odoorpc
664 >>> odoorpc.ODOO.list()
665 ['foo', 'bar']
666
667 Use the :func:`save <odoorpc.ODOO.save>` and
668 :func:`load <odoorpc.ODOO.load>` methods to manage such sessions.
669
670 *Python 2:*
671
672 :raise: `IOError`
673
674 *Python 3:*
675
676 :raise: `PermissionError`
677 :raise: `FileNotFoundError`
678 """
679 sessions = session.get_all(rc_file)
680 return [
681 name
682 for name in sessions
683 if sessions[name].get('type') == cls.__name__
684 ]
685 # return session.list(rc_file)
686
687 @classmethod
688 def remove(cls, name, rc_file='~/.odoorpcrc'):
689 """Remove the session identified by `name` from the `rc_file` file:
690
691 .. doctest::
692 :options: +SKIP
693
694 >>> import odoorpc
695 >>> odoorpc.ODOO.remove('foo')
696 True
697
698 *Python 2:*
699
700 :raise: `ValueError` (if the session does not exist)
701 :raise: `IOError`
702
703 *Python 3:*
704
705 :raise: `ValueError` (if the session does not exist)
706 :raise: `PermissionError`
707 :raise: `FileNotFoundError`
708 """
709 data = session.get(name, rc_file)
710 if data.get('type') != cls.__name__:
711 raise error.InternalError(
712 "'{}' session is not of type '{}'".format(name, cls.__name__)
713 )
714 return session.remove(name, rc_file)