-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathodooly.py
More file actions
2497 lines (2133 loc) · 97.5 KB
/
odooly.py
File metadata and controls
2497 lines (2133 loc) · 97.5 KB
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
""" odooly.py -- Odoo client library and command line tool
Author: Florent Xicluna
"""
import _ast
import argparse
import atexit
import datetime
import functools
import json
import os
import re
import shlex
import sys
import time
import traceback
from configparser import ConfigParser
from getpass import getpass
from pathlib import Path
from string import Formatter
from threading import current_thread
from urllib.parse import urlencode, urljoin, urlsplit
try:
import requests
except ImportError:
requests = None
__version__ = '2.6.5'
__all__ = ['Client', 'Env', 'HTTPSession', 'WebAPI', 'Service', 'Json2',
'Printer', 'Error', 'ServerError',
'BaseModel', 'Model', 'BaseRecord', 'Record', 'RecordList',
'format_exception', 'read_config', 'start_odoo_services']
CONF_FILE = Path('odooly.ini')
HIST_FILE = Path('~/.odooly_history').expanduser()
DEFAULT_URL = 'http://localhost:8069/'
ADMIN_USER = 'admin'
SYSTEM_USER = '__system__'
MAXCOL = [79, 179, 9999] # Line length in verbose mode
PP_FORMAT = {'sort_dicts': False, 'width': 120}
USER_AGENT = f'Mozilla/5.0 (X11) odooly.py/{__version__}'
USAGE = """\
Usage (some commands):
env[name] # Return a Model instance
env[name].keys() # List field names of the model
env[name].fields(names=None) # Return details for the fields
env[name].field(name) # Return details for the field
env[name].browse(ids=())
env[name].search(domain)
env[name].search(domain, offset=0, limit=None, order=None)
# Return a RecordList
rec = env[name].get(domain) # Get the Record matching domain
rec.some_field # Return the value of this field
rec.read(fields=None) # Return values for the fields
client.login(user) # Login with another user
client.connect(env_name) # Connect to another env.
client.connect(server=None) # Connect to another server
env.models(name) # List models matching pattern
env.modules(name) # List modules matching pattern
env.install(module1, module2, ...)
env.upgrade(module1, module2, ...)
# Install or upgrade the modules
env.upgrade_cancel() # Reset failed upgrade/install
"""
DOMAIN_OPERATORS = frozenset('!|&')
# Supported operators are:
# =, !=, >, >=, <, <=, like, ilike, in, not like, not ilike, not in,
# =like, =ilike, =?, child_of, parent_of,
# any, not any, # Odoo 17
# not =like, not =ilike, # Odoo 19
_term_re = re.compile(
r'([\w._]+)\s*' r'(=like\b|=ilike\b|=\?|[<>]=?|!?=|'
r'\b(?:like|ilike|in|any|not (?:=?like|=?ilike|in|any)|child_of|parent_of)\b)'
r'(?![?!=<>])\s*(.+)')
# Web methods (not exhaustive)
_web_methods = {
'database': ['backup', 'change_password', 'create',
'drop', 'duplicate', 'list', 'restore'],
'dataset': ['call_button', 'call_kw'],
'session': ['authenticate', 'check', 'destroy', 'get_lang_list', 'get_session_info'],
'webclient': ['version_info'],
}
# RPC methods
_rpc_methods = {
'common': ['login', 'authenticate', 'version'],
'object': ['execute', 'execute_kw'],
}
_cause_message = ("\nThe above exception was the direct cause "
"of the following exception:\n\n")
_pending_state = ('state', 'not in',
['uninstallable', 'uninstalled', 'installed'])
_base_method_params = [
('action_archive', ['ids']),
('action_unarchive', ['ids']),
('copy', ['ids', 'default']),
('create', ['vals_list']),
('get_external_id', ['ids']),
('get_metadata', ['ids']),
('read', ['ids', 'fields', 'load']),
('search', ['domain', 'offset', 'limit', 'order']),
('search_count', ['domain', 'limit']),
('search_read', ['domain', 'fields', 'offset', 'limit', 'order']),
('unlink', ['ids']),
('write', ['ids', 'vals']),
]
_sql_action_code = """\
sql_queries = env.context.get("__sql") or []
result = env.cr.connection.notices
if not env.is_system():
raise UserError("Not allowed")
for query in sql_queries:
env.cr.execute(query)
if not env.cr.description:
result.append(env.cr.statusmessage)
elif not env.cr.rowcount:
result.append({c.name: () for c in env.cr.description})
else:
columns = [c.name for c in env.cr.description]
result.extend(dict(zip(columns, values)) for values in env.cr.fetchall())
log(str({'queries': sql_queries, 'result': result}))
result[:] = []
"""
color_bold = color_comment = color_py = color_repr = str
http_context = None
if os.getenv('ODOOLY_SSL_UNVERIFIED'):
import ssl
http_context = ssl._create_unverified_context()
requests = None
if not requests:
from urllib.request import HTTPCookieProcessor, HTTPSHandler, Request, build_opener
class HTTPSession:
if requests: # requests.Session
def __init__(self):
self._session = requests.Session()
self._session.headers.update({'User-Agent': USER_AGENT, 'Accept': 'application/json'})
def set_auth(self, uri, username, password):
self._session.auth = (username, password)
def _request(self, url, method, data, json, headers, **kw):
resp = self._session.request(method, url, data=data, json=json, headers=headers, **kw)
return resp.raise_for_status() or resp
def _parse_response(self, resp):
is_json = 'json' in resp.headers.get('content-type', '')
return resp.json() if is_json else resp.text
def _parse_error(self, err):
resp = err.response
return (resp.status_code, self._parse_response(resp)) if resp is not None else (0, 0)
else: # urllib.request
def __init__(self):
self._session = build_opener(HTTPCookieProcessor(), HTTPSHandler(context=http_context))
self._session.addheaders = [('User-Agent', USER_AGENT), ('Accept', 'application/json')]
def set_auth(self, uri, username, password):
from urllib.request import HTTPBasicAuthHandler
auth = HTTPBasicAuthHandler()
auth.add_password(None, uri, username, password)
self._session.add_handler(auth)
def _request(self, url, method, data, json, headers, _json=json, **kw):
headers = dict(headers or ())
if json is not None:
headers.setdefault('Content-Type', 'application/json')
if method == 'POST':
data = (urlencode(data) if json is None else _json.dumps(json)).encode()
elif data is not None:
url, data = f'{url}?{urlencode(data)}', None
return self._session.open(Request(url, data=data, headers=headers, method=method))
def _parse_response(self, resp):
is_json = 'json' in resp.headers.get('content-type', '')
return json.load(resp) if is_json else resp.read().decode()
def _parse_error(self, err):
return (err.code, self._parse_response(err)) if hasattr(err, 'code') else (0, 0)
def request(self, url, *, method='POST', data=None, json=None, headers=None):
try:
with self._request(url, method=method, data=data, json=json, headers=headers) as resp:
return resp if method == 'HEAD' else self._parse_response(resp)
except OSError as exc:
status_code, result = self._parse_error(exc)
if result and status_code in (401, 403, 404, 422, 500):
# Unauthorized, Forbidden, NotFound, UnprocessableContent, InternalServerError
if isinstance(result, str):
lines = re.findall(r'>([^>\n]+)<', result) or (status_code, result)
result = {'name': exc.__class__.__name__, 'debug': None,
'arguments': (f'{lines[0]} - {lines[-1]}',)}
raise ServerError({'code': status_code, 'data': result})
raise
Ids, Id1 = type('ids', (list,), {'__slots__': ()}), type('id1', (int,), {'__slots__': ()})
def _memoize(inst, attr, value, doc_values=None):
if hasattr(value, '__get__') and not hasattr(value, '__self__'):
value.__name__ = attr
if doc_values is not None:
value.__doc__.format(*doc_values)
value = value.__get__(inst, type(inst))
inst.__dict__[attr] = value
return value
# Simplified ast.literal_eval which does not parse operators
def _convert(node):
if isinstance(node, _ast.Constant) and node.value.__class__ is not complex:
return node.value
if isinstance(node, _ast.Tuple):
return tuple(map(_convert, node.elts))
if isinstance(node, _ast.List):
return [*map(_convert, node.elts)]
if isinstance(node, _ast.Dict):
return {_convert(k): _convert(v)
for (k, v) in zip(node.keys, node.values)}
if isinstance(node, _ast.UnaryOp):
if isinstance(node.op, _ast.USub):
return -_convert(node.operand)
if isinstance(node.op, _ast.UAdd):
return +_convert(node.operand)
raise ValueError('malformed or disallowed expression')
def literal_eval(expression):
node = compile(expression, '<unknown>', 'eval', _ast.PyCF_ONLY_AST)
return _convert(node.body)
def format_params(params, hide=('passw', 'pwd')):
secret = {key: ... for key in params if any(sub in key for sub in hide)}
return [f'{key}={v!r}' if v != ... else f'{key}=*'
for (key, v) in {**params, **secret}.items()]
def format_exception(exc_type, exc, tb, limit=None, chain=True,
_format_exception=traceback.format_exception, **kw):
"""Format a stack trace and the exception information.
This wrapper is a replacement of ``traceback.format_exception``
which formats the error and traceback received by API.
If `chain` is True, then the original exception is printed too.
"""
values = _format_exception(exc_type, exc, tb, limit=limit, **kw)
server_error = None
if issubclass(exc_type, Error): # Client-side
values = [f"{exc}\n"]
elif issubclass(exc_type, OSError): # HTTPError (requests or urllib)
values = [f"{exc_type.__name__}: {exc}\n"]
elif issubclass(exc_type, ServerError): # JSON-RPC or Web API
server_error = exc.args[0]['data']
print_tb = not server_error.get('name', '').startswith(('odoo.', 'werkzeug.'))
if server_error:
# Format readable API errors
try:
message = str(server_error['arguments'][0])
except Exception:
message = str(server_error['arguments'])
fault = f"{server_error['name']}: {message}"
tb = print_tb and not message.startswith('FATAL:') and server_error['debug']
if chain:
values = [tb or fault, _cause_message] + values
values[-1] = fault
else:
values = [tb or fault]
return values
def read_config(section=None):
"""Read the environment settings from the configuration file.
Config file ``odooly.ini`` contains a `section` for each environment.
Each section provides parameters for the connection: ``server``,
``username`` and (optional) ``database``, ``password`` and ``api_key``.
As an alternative, server can be declared with 4 parameters:
``scheme / host / port / protocol``.
Default values are read from the ``[DEFAULT]`` section. If the ``password``
is not set or is empty, it is requested on login.
Return tuple ``(server, db or None, user, password or None, api_key or None)``.
Without argument, it returns the list of configured environments.
"""
with Client._config_file.open() as f:
(p := ConfigParser()).read_file(f)
if section is None:
return p.sections()
server = (env := dict(p.items(section))).get('server')
if (scheme := env.get('scheme', 'http')) == 'local':
server = shlex.split(server or env.get('options', ''))
elif not server:
protocol = env.get('protocol', 'web')
server = f"{scheme}://{env['host']}:{env['port']}/{protocol}"
return (server, env.get('database', ''), env['username'], env.get('password'), env.get('api_key'))
def start_odoo_services(options=None, appname=None):
"""Initialize the Odoo services.
Import the ``odoo`` Python package and load the Odoo services.
The argument `options` receives the command line arguments
for ``odoo``. Example:
``['-c', '/path/to/odoo-server.conf', '--without-demo', 'all']``.
Return the ``odoo`` package.
"""
import odoo
if not hasattr(odoo, "_get_pool"):
os.putenv('TZ', 'UTC')
if appname is not None:
os.putenv('PGAPPNAME', appname)
odoo.tools.config.parse_config(options or [])
if odoo.release.version_info < (15,):
odoo.api.Environment.reset()
elif odoo.release.version_info > (19, 2):
import odoo.http.router
odoo.http.dispatch_rpc = odoo.http.router.dispatch_rpc
odoo._get_pool = odoo.modules.registry.Registry
def close_all():
for db in odoo._get_pool.registries.keys():
odoo.sql_db.close_db(db)
atexit.register(close_all)
return odoo
def issearchdomain(arg):
"""Check if the argument is a search domain.
Examples:
- ``[('name', '=', 'mushroom'), ('state', '!=', 'draft')]``
- ``['name = mushroom', 'state != draft']``
- ``[]``
"""
return isinstance(arg, list) and not (arg and (
# Not a list of ids: [1, 2, 3]
isinstance(arg[0], int) or
# Not a list of ids as str: ['1', '2', '3']
(isinstance(arg[0], str) and arg[0].isdigit())))
def searchargs(params, kwargs=None):
"""Compute the 'search' parameters."""
if not params:
return ([],)
if not isinstance(domain := params[0], list):
return params
for (idx, term) in enumerate(domain):
if isinstance(term, str) and term not in DOMAIN_OPERATORS:
if not (m := _term_re.match(term.strip())):
raise ValueError(f"Cannot parse term {term!r}")
(field, operator, value) = m.groups()
try:
value = literal_eval(value)
except Exception:
pass # Interpret the value as a string
domain[idx] = (field, operator, value)
params = (domain,) + params[1:]
if kwargs and len(params) == 1:
args = (kwargs.pop('offset', 0),
kwargs.pop('limit', None),
kwargs.pop('order', None))
if any(args):
params += args
return params
def extract_http_response(method, result, regex):
if method == 'HEAD':
return result.url
found = re.search(regex or r'odoo._*session_info_* = (.*);', result)
return found and (found.group(1) if regex else json.loads(found.group(1)))
class partial(functools.partial):
__slots__ = ()
def __repr__(self):
# Hide arguments
return f"{self.__class__.__name__}({self.func!r}, ...)"
class Error(Exception):
"""An Odooly error."""
class ServerError(Exception):
"""An error received from the server."""
class Printer:
width = None
def _print_(self, message, _prefix):
cols = self.width - len(_prefix) - 1
suffix = f"... L={len(message)}" if len(message) > cols else ""
xch = message[:cols - len(suffix)] + suffix
print(color_comment(f"{_prefix} {xch}"))
print_sent = functools.partialmethod(_print_, _prefix=' >')
print_recv = functools.partialmethod(_print_, _prefix='<--')
def __bool__(self):
return bool(self.width)
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
if exc_type:
if issubclass(exc_type, ServerError):
exc = exc.args[0]["data"]["name"]
self.print_recv(f"{exc_type.__name__}: {exc}")
class WebAPI:
"""A wrapper around Web endpoints.
The connected endpoints are exposed on the Client instance.
Argument `client` is the connected Client.
Argument `endpoint` is the name of the service
(examples: ``"web/database"``, ``"web/session"``).
Argument `methods` is the list of methods which should be
exposed on this endpoint. Use ``dir(...)`` on the
instance to list them.
"""
_methods = ()
def __init__(self, client, endpoint, methods):
self._dispatch = client._proxy_web(endpoint)
self._server = urljoin(client._server, '/')
self._endpoint = f'/{endpoint}'
self._methods = [*methods]
self._printer = client._printer
def __repr__(self):
return f"<WebAPI '{self._server[:-1]}{self._endpoint}'>"
def __dir__(self):
return sorted(self._methods)
def __getattr__(self, name):
def wrapper(self, _func=None, **params):
return self._request(f'{name}/{_func}' if _func else name, params)
return _memoize(self, name, wrapper)
def _request(self, path, params=None):
if not self._printer:
return self._dispatch(path, params)
if self._endpoint == '/doc':
snt = [f'GET /doc/{path}.json']
else:
snt = [f'POST {self._endpoint}/{path}'] + format_params(params)
with self._printer as log:
log.print_sent(' '.join(snt))
log.print_recv(repr(res := self._dispatch(path, params)))
return res
class Service:
"""A wrapper around RPC endpoints.
The connected endpoints are exposed on the Client instance.
The `client` argument is the connected Client.
The `endpoint` argument is the name of the service
(examples: ``"object"``, ``"common"``). The `methods` is the list of methods
which should be exposed on this endpoint. Use ``dir(...)`` on the
instance to list them.
"""
_methods = ()
def __init__(self, client, endpoint, methods):
self._dispatch = client._proxy(endpoint)
self._rpcpath = client._server
self._endpoint = endpoint
self._methods = methods
self._printer = client._printer
def __repr__(self):
return f"<Service '{self._rpcpath}|{self._endpoint}'>"
def __dir__(self):
return sorted(self._methods)
def __getattr__(self, name):
if name not in self._methods:
raise AttributeError(f"'Service' object has no attribute {name!r}")
def sanitize(args):
if len(args) > 2:
args = args[:2] + ('*',) + args[3:]
return ', '.join(repr(arg) for arg in args)
def wrapper(self, *args):
if not self._printer:
return self._dispatch(name, args)
with self._printer as log:
log.print_sent(f"{self._endpoint}.{name}({sanitize(args)})")
log.print_recv(repr(res := self._dispatch(name, args)))
return res
return _memoize(self, name, wrapper)
class Json2:
"""A connection to Json-2 API
Added in Odoo 19.
"""
_protocol_name = 'JSON-2'
_endpoint = '/json/2'
_doc_endpoint = '/doc-bearer'
def __init__(self, client, database, api_key):
self._http = HTTPSession()
self._server = urljoin(client._server, '/')
self._headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json',
'X-Odoo-Database': database or '',
}
self._method_params = {'base': dict(_base_method_params)}
self._printer = client._printer
def doc(self, model):
"""Documentation of the `model`."""
model_doc = self._request(f'{self._doc_endpoint}/{model}.json')
if model not in self._method_params:
method_params = Model._parse_doc_methods(model_doc)
self._method_params[model] = dict(method_params)
return model_doc
def _methods(self, model):
if model not in self._method_params:
self.doc(model)
return self._method_params[model]
def _prepare_params(self, model, method, args, kwargs):
if not args:
return {**kwargs}
if len(args) == 1 and args[0].__class__ in (Ids, Id1):
return {'ids': args[0], **kwargs}
if not (arg_names := self._method_params['base'].get(method)):
arg_names = self._methods(model).setdefault(method, ())
params = dict(zip(arg_names, args))
params.update(kwargs)
if len(args) > len(arg_names) and self._printer:
print(f"Method {method!r} on {model!r} called with extra args: {args[len(arg_names):]}")
return params
def __call__(self, model, method, args, kw=None):
"""Execute API call on the `model`."""
params = self._prepare_params(model, method, args, kw or {})
return self._request(f'{self._endpoint}/{model}/{method}', params)
def __repr__(self):
return f"<Json2 '{self._server[:-1]}{self._endpoint}'>"
def _check(self, uid=None):
url = urljoin(self._server, f'{self._endpoint}/res.users/context_get')
try:
context = self._http.request(url, json={}, headers=self._headers)
except ServerError:
return False
return self if (not uid or uid == context['uid']) else False
def _request(self, path, params=None):
url = urljoin(self._server, path)
verb = 'GET' if params is None else 'POST'
if not self._printer:
return self._http.request(url, method=verb, json=params, headers=self._headers)
with self._printer as log:
log.print_sent(' '.join([verb, path] + format_params(params or {})))
res = self._http.request(url, method=verb, json=params, headers=self._headers)
log.print_recv(repr(res))
return res
class Env:
"""An environment wraps data for Odoo models and records:
- :attr:`db_name`, the current database;
- :attr:`uid`, the current user id;
- :attr:`context`, the current context dictionary.
To retrieve an instance of ``some.model``:
>>> env["some.model"]
"""
name = uid = user = session_info = _api_key = _doc = _json2 = _access_models = None
_class_ids = Ids, Id1
_cache = {}
def __new__(cls, client, db_name=()):
if db_name:
env = cls._cache.get((Env, db_name, client._server))
if env and env.client == client:
return env
if not db_name or client.env.db_name:
env = object.__new__(cls)
env.client, env.db_name, env.context = client, db_name, {}
else:
env, env.db_name = client.env, db_name
if db_name:
env._model_names = env._cache_get('model_names', dict)
env._models = {}
return env
def __contains__(self, name):
"""Test wether this model exists."""
return name in self.models(name)
def __getitem__(self, name):
"""Return the :class:`Model` for the given ``name``."""
return self._get(name)
def __iter__(self):
"""Return an iterator on model names."""
return iter(self.models())
def __len__(self):
"""Return the size of the model registry."""
return len(self.models())
def __bool__(self):
return True
__eq__ = object.__eq__
__ne__ = object.__ne__
__hash__ = object.__hash__
def __repr__(self):
return f"<Env '{self.user.login if self.uid else ''}@{self.db_name}'>"
def _check_user_password(self, user, password, api_key):
if self.client._object and not self.db_name:
raise Error('Error: Not connected')
assert isinstance(user, str) and user
if user == SYSTEM_USER and self.uid and not password:
info = self.client._authenticate_system()
return info['uid'], password, info
# Read from cache
auth_cache = self._cache_get('auth', dict)
(uid, pwcache) = auth_cache.get(user) or (None, None)
password = password or pwcache
# Ask for password
if not password and not api_key:
password = getpass(f"Password for '{color_bold(user)}': ")
if not self.client._object:
try: # Standard Web or JSON-2 authentication
info = self.client._authenticate(self.db_name, user, password, api_key)
uid = info['uid']
except Exception as exc:
if 'does not exist' in str(exc): # Heuristic
raise Error('Error: Database does not exist')
raise
else: # Login through RPC Service (deprecated)
if not uid:
uid = self.client.common.login(self.db_name, user, api_key or password)
if uid:
args = self.db_name, uid, api_key or password, 'res.users', 'context_get', ()
info = {'uid': uid, 'user_context': self.client._object.execute_kw(*args)}
if not uid: # Failed
if user in auth_cache:
del auth_cache[user]
raise Error('Error: Invalid username or password')
# Discovered database name
if not self.db_name:
self.db_name = info.get('db') or ()
# Set the cache for authentication
self._cache_set('auth', auth_cache)
self.refresh()
if not self.uid:
# Cache the unauthenticated Env and the client
self._cache_set(Env, self)
# Update credentials in cache
auth_cache[user] = uid, password
return uid, password, info
def set_api_key(self, api_key, store=True):
"""Configure methods to use an API key."""
def env_auth(method): # Authenticated endpoints
return partial(method, self.db_name, self.uid, api_key)
if self.client.web and self.client.version_info >= 19.0:
self._json2 = Json2(self.client, self.db_name, api_key)._check(self.uid)
self._doc = (self._json2 or self.client.web).doc
try:
self._doc('res.device')
except ServerError:
self._doc = None
prev_protocol = getattr(self, '_execute_kw', ...)
if self.client._object: # RPC endpoint if available
self._execute_kw = env_auth(self.client._object.execute_kw)
self._execute_kw._protocol_name = self.client._proxy._protocol_name
else: # Otherwise, use JSON-2 or WebAPI
self._execute_kw = self._json2 or self._call_kw
if prev_protocol not in (self._execute_kw._protocol_name, ...):
self.client.connect()
self._api_key = api_key if store else None
return api_key
def _configure(self, uid, user, password, api_key, context, session):
env = Env(self.client)
(env.db_name, env.name) = (self.db_name, self.name)
env._model_names = self._model_names
env._models = {}
# Setup uid and user
if isinstance(user, Record):
user = user.login
env.uid = uid
env.user = Record(env._get('res.users', False), uid)
env.context = dict(context)
env.session_info = session
if user:
assert isinstance(user, str), repr(user)
env.user.__dict__['login'] = user
# Set API methods
if uid != self.uid or (api_key and api_key != self._api_key):
env.set_api_key(api_key or password, bool(api_key))
else: # Copy methods
for attr in 'access_models', 'api_key', 'doc', 'execute_kw', 'json2':
setattr(env, f'_{attr}', getattr(self, f'_{attr}'))
return env
@property
def odoo_env(self):
"""Return a server Environment."""
return self.client._server.api.Environment(self.cr, self.uid, self.context)
@property
def cr(self):
"""Return a cursor on the database."""
return self.__dict__.get('cr') or _memoize(self, 'cr', self.registry.cursor())
@property
def registry(self):
"""Return the environment's registry."""
return self.client._server._get_pool(self.db_name)
def __call__(self, user=None, password=None, api_key=None, context=None):
"""Return an environment based on ``self`` with modified parameters."""
if user is not None:
(uid, password, session) = self._check_user_password(user, password, api_key)
if context is None:
context = session.get('user_context') or {}
elif context is not None:
(uid, user, session) = (self.uid, self.user, self.session_info)
else:
return self
env_key = bytes.fromhex(f"{uid:08x}{hash(json.dumps(context, sort_keys=1)) % 2**32:08x}")
if (env := self._cache_get(env_key)) is None:
env = self._configure(uid, user, password, api_key, context, session)
env._cache_set(env_key, env)
return env
def sudo(self, user=None):
"""Attach to the provided user, or Superuser."""
if user is None:
if self.client._object or not (self.session_info or {}).get('is_system'):
user = ADMIN_USER
else:
user = SYSTEM_USER
return self(user=user)
def ref(self, xml_id):
"""Return the record for the given ``xml_id`` external ID."""
(module, name) = xml_id.split('.')
data = self._get('ir.model.data', False).read(
[('module', '=', module), ('name', '=', name)], 'model res_id')
if data:
assert len(data) == 1
return Record(self[data[0]['model']], data[0]['res_id'])
@property
def lang(self):
"""Return the current language code."""
return self.context.get('lang')
def refresh(self):
db_key, preserve = (self.db_name, self.client._server), ('auth', Env)
for key in [*self._cache]:
if key[1:] == db_key and key[0] not in preserve and self._cache[key] != self:
del self._cache[key]
self._access_models = None
self._model_names = self._cache_set('model_names', {})
self._models = {}
if self._json2:
self._json2._method_params = {'base': dict(_base_method_params)}
def _cache_get(self, key, func=None):
try:
return self._cache[key, self.db_name, self.client._server]
except KeyError:
pass
if func is not None:
return self._cache_set(key, func())
def _cache_set(self, key, value, db_name=None):
self._cache[key, db_name or self.db_name, self.client._server] = value
return value
def _is_identitycheck(self, result):
return hasattr(result, 'get') and result.get('res_model') == 'res.users.identitycheck'
def _identitycheck(self, result):
assert self.client.version_info >= 14.0, f'Not supported: Odoo {self.client.version_info}'
idcheck = self._get(result['res_model'], transient=True).get(result['res_id'])
password = self._cache_get('auth')[self.user.login][1]
result = None
while not result:
try:
password = password or getpass(f"Password for '{color_bold(self.user.login)}': ")
except (KeyboardInterrupt, EOFError):
print()
raise Error("Security Control - FAILED")
if self.client.version_info < 19.0:
idcheck.password = password
try:
# Odoo >= 19 read from context
result = idcheck.with_context(password=password).run_check()
except ServerError as exc:
error = exc.args[0]['data']
if not self.client._is_interactive() or error['name'] != 'odoo.exceptions.UserError':
raise
password = None
print(error['message'])
if self.client._is_interactive():
print("Security Control - PASSED")
return result
def _call_kw(self, model, method, args, kw=None):
if self.uid != self.client._session_uid:
password = self._cache_get('auth')[self.user.login][1]
if self.user.login == SYSTEM_USER and not password:
self.client._authenticate_system()
else:
self.client._authenticate_session(self.db_name, self.user.login, password)
return self.client.web_dataset.call_kw(model=model, method=method, args=args, kwargs=kw or {})
_call_kw._protocol_name = 'Web API'
def execute(self, obj, method, *params, **kwargs):
"""Wrapper around ``/web/dataset/call_kw`` Webclient endpoint,
or ``/json/2`` API endpoint or ``object.execute_kw`` RPC method.
Argument `method` is the name of a standard ``Model`` method
or a specific method available on this `obj`.
Method `params` are accepted. If needed, keyword
arguments are collected in `kwargs`.
"""
assert self.uid, 'Not connected'
assert isinstance(obj, str) and isinstance(method, str) and method != 'browse'
order_ids = single_id = False
if method == 'read':
assert params, 'Missing parameter'
if not isinstance(params[0], list):
single_id = True
ids = [params[0]] if params[0] else False
elif params[0] and issearchdomain(params[0]):
# Combine search+read
method, [ids] = 'search_read', searchargs(params[:1])
else:
order_ids = kwargs.pop('order', False) and params[0]
ids = sorted({*params[0]} - {False})
if not ids and order_ids:
return [False] * len(order_ids)
if not ids:
return ids
params = (ids,) + params[1:]
elif method == 'search':
# Accept keyword arguments for the search method
params = searchargs(params, kwargs)
elif method == 'search_count':
params = searchargs(params)
elif method == 'search_read':
params = searchargs(params[:1]) + params[1:]
kw = (({**kwargs, 'context': self.context},)
if self.context else (kwargs and ({**kwargs},) or ()))
if self.client._use_call_button and method in ('create', 'write', 'unlink'):
return self.client.web_dataset.call_button(model=obj, method=method, args=params, kwargs=kw[0])
res = self._execute_kw(obj, method, params, *kw)
if self._is_identitycheck(res):
res = self._identitycheck(res)
if order_ids:
# Results were not in the same order as the IDs
# in case of missing records or duplicate ID
resdic = {val['id']: val for val in res}
res = [resdic.get(id_, False) for id_ in order_ids]
return (res or [None])[0] if single_id else res
def access(self, model_name, mode="read"):
"""Check if the user has access to this model.
Optional argument `mode` is the access mode to check. Valid values
are ``read``, ``write``, ``create`` and ``unlink``. If omitted,
the ``read`` mode is checked. Return a boolean.
"""
try:
self.execute('ir.model.access', 'check', model_name, mode)
return True
except Exception:
return False
def _models_get(self, name, check, transient):
if name not in self._model_names:
if check:
raise KeyError(name)
self._model_names[name] = transient
try:
return self._models[name]
except KeyError:
self._models[name] = Model._new(self, name)
return self._models[name]
def models(self, name='', transient=False):
"""Search Odoo models.
The argument `name` is a pattern to filter the models returned.
If omitted, all models are returned.
The return value is a sorted list of model names.
"""
if self._access_models is None:
ir_model = self._get('ir.model', False)
domain = [('abstract', '=', False)] if 'abstract' in ir_model._keys else [] # Odoo 19
try:
models = ir_model.search_read(domain, ('model', 'transient'))
except ServerError:
# Only Odoo 15 prevents non-admin user to retrieve models
models = ir_model.get_available_models() if self.client.version_info >= 16.0 else {}
self._model_names.update({m['model']: m.get('transient', False) for m in models})
self._access_models = bool(models)
return sorted(mod for mod, is_transient in self._model_names.items()
if name in mod and transient == is_transient)
def _get(self, name, check=True, transient=False):
"""Return a :class:`Model` instance.
The argument `name` is the name of the model. If the optional
argument `check` is :const:`False`, no validity check is done.
"""
check = check and not transient and self._access_models is not False
try:
return self._models_get(name, check, transient=transient)
except KeyError:
model_names = self.models(name)
if name in self._model_names or not self._access_models:
return self._models_get(name, self._access_models, transient=transient)
if model_names:
errmsg = 'Model not found. These models exist:'
else:
errmsg = f'Model not found: {name}'
raise Error('\n * '.join([errmsg] + model_names))
def modules(self, name='', installed=None):
"""Return a dictionary of modules.
The optional argument `name` is a pattern to filter the modules.
If the boolean argument `installed` is :const:`True`, the modules
which are "Not Installed" or "Not Installable" are omitted. If
the argument is :const:`False`, only these modules are returned.
If argument `installed` is omitted, all modules are returned.
The return value is a dictionary where module names are grouped in
lists according to their ``state``.
"""
if isinstance(name, str):
domain = [('name', 'like', name)]
else:
domain = name
if installed is not None:
op = 'not in' if installed else 'in'
domain.append(('state', op, ['uninstalled', 'uninstallable']))
ir_module = self._get('ir.module.module', False)
if mods := ir_module.read(domain, 'name state'):
res = {}
for mod in mods:
if mod['state'] not in res:
res[mod['state']] = []