forked from tinyerp/odooly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
odooly.py
1996 lines (1719 loc) · 73.2 KB
/
odooly.py
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
# -*- coding: utf-8 -*-
""" odooly.py -- Odoo / OpenERP client library and command line tool
Author: Florent Xicluna
"""
import _ast
import atexit
import csv
import functools
import json
import optparse
import os
import re
import shlex
import sys
import time
import traceback
PY2 = (sys.version_info[0] == 2)
if not PY2: # Python 3
from configparser import ConfigParser
from threading import current_thread
from urllib.request import Request, urlopen
from xmlrpc.client import Fault, ServerProxy, MININT, MAXINT
else: # Python 2
from ConfigParser import SafeConfigParser as ConfigParser
from threading import currentThread as current_thread
from urllib2 import Request, urlopen
from xmlrpclib import Fault, ServerProxy, MININT, MAXINT
try:
import requests
except ImportError:
requests = None
__version__ = '2.1.9'
__all__ = ['Client', 'Env', 'Service', 'BaseModel', 'Model',
'BaseRecord', 'Record', 'RecordList',
'format_exception', 'read_config', 'start_odoo_services']
CONF_FILE = 'odooly.ini'
HIST_FILE = os.path.expanduser('~/.odooly_history')
DEFAULT_URL = 'http://localhost:8069/xmlrpc'
DEFAULT_DB = 'odoo'
DEFAULT_USER = 'admin'
SUPERUSER_ID = 1
MAXCOL = [79, 179, 9999] # Line length in verbose mode
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) # Connect to another env.
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
"""
DOMAIN_OPERATORS = frozenset('!|&')
# Supported operators are:
# =, !=, >, >=, <, <=, like, ilike, in, not like, not ilike, not in,
# child_of, =like, =ilike, =?
_term_re = re.compile(
r'([\w._]+)\s*' r'(=(?:like|ilike|\?)|[<>]=?|!?=(?!=)'
r'|(?<= )(?:like|ilike|in|not like|not ilike|not in|child_of))' r'\s*(.*)')
_fields_re = re.compile(r'(?:[^%]|^)%\(([^)]+)\)')
# Published object methods
_methods = {
'db': ['create_database', 'duplicate_database', 'db_exist',
'drop', 'dump', 'restore', 'rename', 'list', 'list_lang',
'change_admin_password', 'server_version', 'migrate_databases'],
'common': ['about', 'login', 'timezone_get',
'authenticate', 'version', 'set_loglevel'],
'object': ['execute', 'execute_kw', 'exec_workflow'],
'report': ['render_report', 'report', 'report_get'], # < 11.0
}
# New 6.1: (db) create_database db_exist,
# (common) authenticate version set_loglevel
# (object) execute_kw, (report) render_report
# New 7.0: (db) duplicate_database
_obsolete_methods = {
'db': ['create', 'get_progress'], # < 8.0
'common': ['check_connectivity', 'get_available_updates', 'get_os_time',
'get_migration_scripts', 'get_server_environment',
'get_sqlcount', 'get_stats',
'list_http_services', 'login_message'], # < 8.0
'wizard': ['execute', 'create'], # < 7.0
}
_cause_message = ("\nThe above exception was the direct cause "
"of the following exception:\n\n")
_pending_state = ('state', 'not in',
['uninstallable', 'uninstalled', 'installed'])
if PY2:
int_types = int, long
class _DictWriter(csv.DictWriter):
"""Unicode CSV Writer, which encodes output to UTF-8."""
def _dict_to_list(self, rowdict):
rowlst = csv.DictWriter._dict_to_list(self, rowdict)
return [cell.encode('utf-8') if hasattr(cell, 'encode') else cell
for cell in rowlst]
else: # Python 3
basestring = str
int_types = int
_DictWriter = csv.DictWriter
seq_types = (list, tuple)
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__ %= doc_values
value = value.__get__(inst, type(inst))
inst.__dict__[attr] = value
return value
_ast_node_attrs = []
for (cls, attr) in [('Constant', 'value'), # Python >= 3.7
('NameConstant', 'value'), # Python >= 3.4 (singletons)
('Str', 's'), # Python <= 3.7
('Num', 'n')]: # Python <= 3.7
if hasattr(_ast, cls):
_ast_node_attrs.append((getattr(_ast, cls), attr))
# Simplified ast.literal_eval which does not parse operators
def _convert(node, _consts={'None': None, 'True': True, 'False': False}):
for (ast_class, node_attr) in _ast_node_attrs:
if isinstance(node, ast_class):
return getattr(node, node_attr)
if isinstance(node, _ast.Tuple):
return tuple(map(_convert, node.elts))
if isinstance(node, _ast.List):
return list(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.Name) and node.id in _consts:
return _consts[node.id] # Python <= 3.3
if isinstance(node, _ast.UnaryOp): # Python >= 3
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, _octal_digits=frozenset('01234567')):
node = compile(expression, '<unknown>', 'eval', _ast.PyCF_ONLY_AST)
if expression[:1] == '0' and expression[1:2] in _octal_digits:
raise SyntaxError('unsupported octal notation')
value = _convert(node.body)
if isinstance(value, int_types) and not MININT <= value <= MAXINT:
raise ValueError('overflow, int exceeds XML-RPC limits')
return value
def is_list_of_dict(iterator):
"""Return True if the first non-false item is a dict."""
for item in iterator:
if item:
return isinstance(item, dict)
return False
def format_exception(exc_type, exc, tb, limit=None, chain=True,
_format_exception=traceback.format_exception):
"""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 XML-RPC/JSON-RPC.
If `chain` is True, then the original exception is printed too.
"""
values = _format_exception(exc_type, exc, tb, limit=limit)
server_error = None
if issubclass(exc_type, Error): # Client-side
values = [str(exc) + '\n']
elif issubclass(exc_type, ServerError): # JSON-RPC
server_error = exc.args[0]['data']
elif (issubclass(exc_type, Fault) and # XML-RPC
isinstance(exc.faultCode, basestring)):
(message, tb) = (exc.faultCode, exc.faultString)
exc_name = exc_type.__name__
warning = message.startswith('warning --')
if warning:
message = re.sub(r'\((.*), None\)$',
lambda m: literal_eval(m.group(1)),
message.split(None, 2)[2])
else: # ValidationError, DatabaseExists, etc ...
parts = message.rsplit('\n', 1)
if parts[-1] == 'None':
warning, message = True, parts[0]
last_line = tb.rstrip().rsplit('\n', 1)[-1]
if last_line.startswith('odoo.'):
warning, exc_name = True, last_line.split(':', 1)[0]
server_error = {
'exception_type': 'warning' if warning else 'internal_error',
'name': exc_name,
'arguments': (message,),
'debug': tb,
}
if server_error:
# Format readable XML-RPC and JSON-RPC errors
message = server_error['arguments'][0]
fault = '%s: %s' % (server_error['name'], message)
if (server_error['exception_type'] != 'internal_error' or
message.startswith('FATAL:')):
server_tb = None
else:
server_tb = server_error['debug']
if chain:
values = [server_tb or fault, _cause_message] + values
values[-1] = fault
else:
values = [server_tb or fault]
return values
def read_config(section=None):
"""Read the environment settings from the configuration file.
The config file ``odooly.ini`` contains a `section` for each environment.
Each section provides parameters for the connection: ``host``, ``port``,
``database``, ``username`` and (optional) ``password``. Default values
are read from the ``[DEFAULT]`` section. If the ``password`` is not in
the configuration file, it is requested on login.
Return a tuple ``(server, db, user, password or None)``.
Without argument, it returns the list of configured environments.
"""
p = ConfigParser()
with open(Client._config_file) as f:
p.readfp(f) if PY2 else p.read_file(f)
if section is None:
return p.sections()
env = dict(p.items(section))
scheme = env.get('scheme', 'http')
if scheme == 'local':
server = shlex.split(env.get('options', ''))
else:
protocol = env.get('protocol', 'xmlrpc')
server = '%s://%s:%s/%s' % (scheme, env['host'], env['port'], protocol)
return (server, env['database'], env['username'], env.get('password'))
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.
"""
try:
import openerp as odoo
except ImportError:
import odoo
odoo._api_v7 = odoo.release.version_info < (8,)
if not (odoo._api_v7 and odoo.osv.osv.service):
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 < (7,):
odoo.netsvc.init_logger()
odoo.osv.osv.start_object_proxy()
odoo.service.web_services.start_web_services()
elif odoo._api_v7:
odoo.service.start_internal()
else: # Odoo v8
odoo.api.Environment.reset()
try:
manager_class = odoo.modules.registry.RegistryManager
odoo._get_pool = manager_class.get
except AttributeError: # Odoo >= 10
odoo._get_pool = manager_class = odoo.modules.registry.Registry
def close_all():
for db in manager_class.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_types) or
# Not a list of ids as str: ['1', '2', '3']
(isinstance(arg[0], basestring) and arg[0].isdigit())))
def searchargs(params, kwargs=None):
"""Compute the 'search' parameters."""
if not params:
return ([],)
domain = params[0]
if not isinstance(domain, list):
return params
for (idx, term) in enumerate(domain):
if isinstance(term, basestring) and term not in DOMAIN_OPERATORS:
m = _term_re.match(term.strip())
if not m:
raise ValueError('Cannot parse term %r' % term)
(field, operator, value) = m.groups()
try:
value = literal_eval(value)
except Exception:
# Interpret the value as a string
pass
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
if os.getenv('ODOOLY_SSL_UNVERIFIED'):
import ssl
def urlopen(url, _urlopen=urlopen):
return _urlopen(url, context=ssl._create_unverified_context())
def ServerProxy(url, transport, allow_none, _ServerProxy=ServerProxy):
return _ServerProxy(url, transport=transport, allow_none=allow_none,
context=ssl._create_unverified_context())
requests = False
if requests:
def http_post(url, data, headers={'Content-Type': 'application/json'}):
resp = requests.post(url, data=data, headers=headers)
return resp.json()
else:
def http_post(url, data, headers={'Content-Type': 'application/json'}):
request = Request(url, data=data, headers=headers)
resp = urlopen(request)
return json.load(resp)
def dispatch_jsonrpc(url, service_name, method, args):
data = {
'jsonrpc': '2.0',
'method': 'call',
'params': {'service': service_name, 'method': method, 'args': args},
'id': '%04x%010x' % (os.getpid(), (int(time.time() * 1E6) % 2**40)),
}
resp = http_post(url, json.dumps(data).encode('ascii'))
if resp.get('error'):
raise ServerError(resp['error'])
return resp['result']
class partial(functools.partial):
__slots__ = ()
def __repr__(self):
# Hide arguments on Python 3
return '%s(%r, ...)' % (self.__class__.__name__, self.func)
class Error(Exception):
"""An Odooly error."""
class ServerError(Exception):
"""An error received from the server."""
class Service(object):
"""A wrapper around XML-RPC endpoints.
The connected endpoints are exposed on the Client instance.
The `server` argument is the URL of the server (scheme+host+port).
If `server` is an ``odoo`` Python package, it is used to connect to the
local server. The `endpoint` argument is the name of the service
(examples: ``"object"``, ``"db"``). 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, verbose=False):
self._dispatch = client._proxy(endpoint)
self._rpcpath = client._server
self._endpoint = endpoint
self._methods = methods
self._verbose = verbose
def __repr__(self):
return "<Service '%s|%s'>" % (self._rpcpath, self._endpoint)
__str__ = __repr__
def __dir__(self):
return sorted(self._methods)
def __getattr__(self, name):
if name not in self._methods:
raise AttributeError("'Service' object has no attribute %r" % name)
if self._verbose:
def sanitize(args):
if self._endpoint != 'db' and len(args) > 2:
args = list(args)
args[2] = '*'
return args
maxcol = MAXCOL[min(len(MAXCOL), self._verbose) - 1]
def wrapper(self, *args):
snt = ', '.join([repr(arg) for arg in sanitize(args)])
snt = '%s.%s(%s)' % (self._endpoint, name, snt)
if len(snt) > maxcol:
suffix = '... L=%s' % len(snt)
snt = snt[:maxcol - len(suffix)] + suffix
print('--> ' + snt)
res = self._dispatch(name, args)
rcv = str(res)
if len(rcv) > maxcol:
suffix = '... L=%s' % len(rcv)
rcv = rcv[:maxcol - len(suffix)] + suffix
print('<-- ' + rcv)
return res
else:
wrapper = lambda s, *args: s._dispatch(name, args)
return _memoize(self, name, wrapper)
class Env(object):
"""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 = None
_cache = {}
def __new__(cls, client, db_name=()):
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', set)
env._models = {}
return env
def __contains__(self, name):
"""Test wether the given model exists."""
return name in self._model_names or name in self.models(name)
def __getitem__(self, name):
"""Return the given :class:`Model`."""
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
__nonzero__ = __bool__
__eq__ = object.__eq__
__ne__ = object.__ne__
__hash__ = object.__hash__
def __repr__(self):
return "<Env '%s@%s'>" % (self.user.login if self.uid else '',
self.db_name)
def check_uid(self, uid, password):
"""Check if ``(uid, password)`` is valid.
Return ``uid`` on success, ``False`` on failure.
The invalid entry is removed from the authentication cache.
"""
try:
self.client._object.execute_kw(self.db_name, uid, password,
'ir.model', 'fields_get', ([None],))
except Exception:
auth_cache = self._cache_get('auth')
if uid in auth_cache:
del auth_cache[uid]
uid = False
return uid
def _auth(self, user, password):
assert self.db_name, 'Not connected'
uid = verified = None
if isinstance(user, int_types):
(user, uid) = (uid, user)
auth_cache = self._cache_get('auth', dict)
if not password:
# Read from cache
(uid, password) = auth_cache.get(user or uid) or (uid, None)
# Read from model 'res.users'
if not password and self.access('res.users', 'write'):
domain = [('login', '=', user)] if user else [uid]
obj = self['res.users'].read(domain, 'id login password')
if obj:
uid = obj[0]['id']
user = obj[0]['login']
password = obj[0]['password']
else:
# Invalid user
uid = False
verified = password and uid
# Ask for password
if not password and uid is not False:
from getpass import getpass
if user is None:
name = 'admin' if uid == SUPERUSER_ID else ('UID %d' % uid)
else:
name = user
password = getpass('Password for %r: ' % name)
# Check if password is valid
uid = self.check_uid(uid, password) if (uid and not verified) else uid
if uid is None:
# Do a standard 'login'
try:
uid = self.client.common.login(self.db_name, user, password)
except Exception as exc:
if 'does not exist' in str(exc): # Heuristic
raise Error('Database does not exist')
raise
if not uid:
raise Error('Invalid username or password')
# Update the cache
auth_cache[uid] = (uid, password)
if user:
auth_cache[user] = auth_cache[uid]
return (uid, password)
def _set_credentials(self, uid, password):
def env_auth(method): # Authenticated endpoints
return partial(method, self.db_name, uid, password)
self._execute = env_auth(self.client._object.execute)
self._execute_kw = env_auth(self.client._object.execute_kw)
if self.client._report: # Odoo <= 10
self.exec_workflow = env_auth(self.client._object.exec_workflow)
self.report = env_auth(self.client._report.report)
self.report_get = env_auth(self.client._report.report_get)
self.render_report = env_auth(self.client._report.render_report)
if self.client._wizard: # OpenERP 6.1
self.wizard_execute = env_auth(self.client._wizard.execute)
self.wizard_create = env_auth(self.client._wizard.create)
def _configure(self, uid, user, password, context):
if self.uid: # Create a new Env() instance
env = Env(self.client)
(env.db_name, env.name) = (self.db_name, self.name)
env.context = dict(context)
env._model_names = self._model_names
env._models = {}
else: # Configure the Env() instance
env = self
if uid == self.uid: # Copy methods
for key in ('_execute', '_execute_kw', 'exec_workflow',
'report', 'report_get', 'render_report',
'wizard_execute', 'wizard_create'):
if hasattr(self, key):
setattr(env, key, getattr(self, key))
else: # Create methods
env._set_credentials(uid, password)
# Setup uid and user
if isinstance(user, int_types):
user = 'admin' if uid == SUPERUSER_ID else None
elif isinstance(user, Record):
user = user.login
env.uid = uid
env.user = env._get('res.users', False).browse(uid)
if user:
assert isinstance(user, basestring), repr(user)
env.user.__dict__['login'] = user
env.user._cached_keys.add('login')
return env
@property
def odoo_env(self):
"""Return a server Environment.
Supported since Odoo 8.
"""
assert self.client.version_info >= 8.0, 'Not supported'
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.db.cursor()
if self.client.version_info < 8.0 else 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, context=None):
"""Return an environment based on ``self`` with modified parameters."""
if user is not None:
(uid, password), context = self._auth(user, password), {}
elif context is not None:
(uid, user) = (self.uid, self.user)
else:
return self
env_key = json.dumps((uid, context), sort_keys=True)
env = self._cache_get(env_key)
if env is None:
env = self._configure(uid, user, password, context)
self._cache_set(env_key, env)
return env
def sudo(self, user=SUPERUSER_ID):
"""Attach to the provided user, or SUPERUSER."""
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['ir.model.data'].read(
[('module', '=', module), ('name', '=', name)], 'model res_id')
if data:
assert len(data) == 1
return self[data[0]['model']].browse(data[0]['res_id'])
@property
def lang(self):
"""Return the current language code."""
return self.context.get('lang')
def refresh(self):
db_key = (self.db_name, self.client._server)
for key in list(self._cache):
if key[1:] == db_key and key[0] != 'auth':
del self._cache[key]
self._model_names = self._cache_set('model_names', set())
self._models = {}
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 execute(self, obj, method, *params, **kwargs):
"""Wrapper around ``object.execute_kw`` RPC method.
Argument `method` is the name of an ``osv.osv`` method or
a method available on this `obj`.
Method `params` are allowed. If needed, keyword
arguments are collected in `kwargs`.
"""
assert self.uid, 'Not connected'
assert isinstance(obj, basestring)
assert isinstance(method, basestring) and method != 'browse'
ordered = 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
search_params = searchargs(params[:1], kwargs)
ordered = len(search_params) > 3 and search_params[3]
kw = ({'context': self.context},) if self.context else ()
ids = self._execute_kw(obj, 'search', search_params, *kw)
else:
ordered = kwargs.pop('order', False) and params[0]
ids = set(params[0]) - {False}
if not ids and ordered:
return [False] * len(ordered)
ids = sorted(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)
kw = ((dict(kwargs, context=self.context),)
if self.context else (kwargs and (kwargs,) or ()))
res = self._execute_kw(obj, method, params, *kw)
if ordered:
# The results are not in the same order as the ids
# when received from the server
resdic = {val['id']: val for val in res}
if not isinstance(ordered, list):
ordered = ids
res = [resdic.get(id_, False) for id_ in ordered]
return res[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=False):
if name not in self._model_names:
if check:
raise KeyError(name)
self._model_names.add(name)
try:
return self._models[name]
except KeyError:
self._models[name] = m = Model._new(self, name)
return m
def models(self, name=''):
"""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.
"""
domain = [('model', 'like', name)]
models = self.execute('ir.model', 'read', domain, ('model',))
names = [m['model'] for m in models]
self._model_names.update(names)
return sorted(names)
def _get(self, name, check=True):
"""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.
"""
try:
return self._models_get(name, check)
except KeyError:
model_names = self.models(name)
if name in model_names:
return self._models_get(name, True)
if model_names:
errmsg = 'Model not found. These models exist:'
else:
errmsg = 'Model not found: %s' % (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, basestring):
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)
mods = ir_module.read(domain, 'name state')
if mods:
res = {}
for mod in mods:
if mod['state'] not in res:
res[mod['state']] = []
res[mod['state']].append(mod['name'])
return res
def _upgrade(self, modules, button):
# First, update the list of modules
ir_module = self._get('ir.module.module', False)
updated, added = ir_module.update_list()
if added:
print('%s module(s) added to the list' % added)
# Find modules
sel = modules and ir_module.search([('name', 'in', modules)])
if sel:
# Safety check
mods = ir_module.read([_pending_state], 'name state')
if any(mod['name'] not in modules for mod in mods):
raise Error('Pending actions:\n' + '\n'.join(
(' %(state)s\t%(name)s' % mod) for mod in mods))
if button == 'button_uninstall':
# Safety check
names = ir_module.read([('id', 'in', sel.ids),
'state != installed',
'state != to upgrade',
'state != to remove'], 'name')
if names:
raise Error('Not installed: %s' % ', '.join(names))
# A trick to uninstall dependent add-ons
sel.write({'state': 'to remove'})
try:
# Click upgrade/install/uninstall button
self.execute('ir.module.module', button, sel.ids)
except Exception:
if button == 'button_uninstall':
sel.write({'state': 'installed'})
raise
mods = ir_module.read([_pending_state], 'name state')
if not mods:
if sel:
print('Already up-to-date: %s' %
self.modules([('id', 'in', sel.ids)]))
elif modules:
raise Error('Module(s) not found: %s' % ', '.join(modules))
print('%s module(s) updated' % updated)
return
print('%s module(s) selected' % len(sel))
print('%s module(s) to process:' % len(mods))
for mod in mods:
print(' %(state)s\t%(name)s' % mod)
# Empty the cache for this database
self.refresh()
# Apply scheduled upgrades
self.execute('base.module.upgrade', 'upgrade_module', [])
def upgrade(self, *modules):
"""Press the button ``Upgrade``."""
return self._upgrade(modules, button='button_upgrade')
def install(self, *modules):
"""Press the button ``Install``."""
return self._upgrade(modules, button='button_install')
def uninstall(self, *modules):
"""Press the button ``Uninstall``."""
return self._upgrade(modules, button='button_uninstall')
class Client(object):
"""Connection to an Odoo instance.
This is the top level object.
The `server` is the URL of the instance, like ``http://localhost:8069``.
If `server` is an ``odoo``/``openerp`` Python package, it is used to
connect to the local server.
The `db` is the name of the database and the `user` should exist in the
table ``res.users``. If the `password` is not provided, it will be
asked on login.
"""
_config_file = os.path.join(os.curdir, CONF_FILE)
_globals = None
def __init__(self, server, db=None, user=None, password=None,
transport=None, verbose=False):
self._set_services(server, transport, verbose)
self.env = Env(self)
if db: # Try to login
self.login(user, password=password, database=db)
def _set_services(self, server, transport, verbose):
if isinstance(server, list):
appname = os.path.basename(__file__).rstrip('co')
server = start_odoo_services(server, appname=appname)
elif isinstance(server, basestring) and server[-1:] == '/':
server = server.rstrip('/')
self._server = server
if not isinstance(server, basestring):
assert not transport, 'Not supported'
self._proxy = self._proxy_dispatch
elif '/jsonrpc' in server:
assert not transport, 'Not supported'
self._proxy = self._proxy_jsonrpc
else:
if '/xmlrpc' not in server:
self._server = server + '/xmlrpc'
self._proxy = self._proxy_xmlrpc
self._transport = transport
def get_service(name):
methods = list(_methods[name]) if (name in _methods) else []
if float_version < 8.0:
methods += _obsolete_methods.get(name) or ()
return Service(self, name, methods, verbose=verbose)
float_version = 99.0
self.server_version = ver = get_service('db').server_version()
self.major_version = re.match(r'\d+\.?\d*', ver).group()
self.version_info = float_version = float(self.major_version)
assert float_version > 6.0, 'Not supported: %s' % ver
# Create the RPC services
self.db = get_service('db')
self.common = get_service('common')
self._object = get_service('object')
self._report = get_service('report') if float_version < 11.0 else None
self._wizard = get_service('wizard') if float_version < 7.0 else None
def _proxy_dispatch(self, name):
if self._server._api_v7:
return self._server.netsvc.ExportService.getService(name).dispatch
return partial(self._server.http.dispatch_rpc, name)
def _proxy_xmlrpc(self, name):
proxy = ServerProxy(self._server + '/' + name,
transport=self._transport, allow_none=True)
return proxy._ServerProxy__request
def _proxy_jsonrpc(self, name):
return partial(dispatch_jsonrpc, self._server, name)
@classmethod
def from_config(cls, environment, user=None, verbose=False):
"""Create a connection to a defined environment.
Read the settings from the section ``[environment]`` in the
``odooly.ini`` file and return a connected :class:`Client`.
See :func:`read_config` for details of the configuration file format.
"""
(server, db, conf_user, password) = read_config(environment)
if user and user != conf_user:
password = None
client = cls(server, verbose=verbose)
client.env.name = environment
client.login(user or conf_user, password=password, database=db)
return client
def __repr__(self):
return "<Client '%s#%s'>" % (self._server, self.env.db_name)
def _login(self, user, password=None, database=None):
"""Switch `user` and (optionally) `database`.
If the `password` is not available, it will be asked.
"""
env = self.env
if database:
try:
dbs = self.db.list()
except Exception:
pass # AccessDenied: simply ignore this check
else:
if database not in dbs:
raise Error("Database '%s' does not exist: %s" %