-
Notifications
You must be signed in to change notification settings - Fork 100
/
erppeek.py
1801 lines (1563 loc) · 68 KB
/
erppeek.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 -*-
""" erppeek.py -- Odoo / OpenERP client library and command line tool
Author: Florent Xicluna
(derived from a script by Alan Bell)
"""
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__ = '1.7.1'
__all__ = ['Client', 'Model', 'Record', 'RecordList', 'Service',
'format_exception', 'read_config', 'start_odoo_services']
CONF_FILE = 'erppeek.ini'
HIST_FILE = os.path.expanduser('~/.erppeek_history')
DEFAULT_URL = 'http://localhost:8069/xmlrpc'
DEFAULT_DB = 'odoo'
DEFAULT_USER = 'admin'
MAXCOL = [79, 179, 9999] # Line length in verbose mode
_DEFAULT = object()
USAGE = """\
Usage (some commands):
models(name) # List models matching pattern
model(name) # Return a Model instance
model(name).keys() # List field names of the model
model(name).fields(names=None) # Return details for the fields
model(name).field(name) # Return details for the field
model(name).browse(domain)
model(name).browse(domain, offset=0, limit=None, order=None)
# Return a RecordList
rec = model(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.
client.modules(name) # List modules matching pattern
client.upgrade(module1, module2, ...)
# 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
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
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 mixedcase(s, _cache={}):
"""Convert to MixedCase.
>>> mixedcase('res.company')
'ResCompany'
"""
try:
return _cache[s]
except KeyError:
_cache[s] = s = ''.join([w.capitalize() for w in s.split('.')])
return s
def lowercase(s, _sub=re.compile('[A-Z]').sub,
_repl=(lambda m: '.' + m.group(0).lower()), _cache={}):
"""Convert to lowercase with dots.
>>> lowercase('ResCompany')
'res.company'
"""
try:
return _cache[s]
except KeyError:
_cache[s] = s = _sub(_repl, s).lstrip('.')
return s
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, 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.exceptions'):
exc_name = 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 ``erppeek.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:
odoo._manager_class = odoo.modules.registry.RegistryManager
odoo._get_pool = odoo._manager_class.get
except AttributeError: # Odoo >= 10
odoo._manager_class = odoo.modules.registry.Registry
odoo._get_pool = odoo._manager_class
def close_all():
for db in odoo._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, context=None, api_v9=False):
"""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 or context) and len(params) == 1:
args = (kwargs.pop('offset', 0),
kwargs.pop('limit', None),
kwargs.pop('order', None))
if context:
# Order of the arguments was different with Odoo 9 and older
params += args + ((context,) if api_v9 else (False, context))
elif any(args):
params += args
return params
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 Error(Exception):
"""An ERPpeek 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)
def __del__(self):
if hasattr(self, 'close'):
self.close()
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 (>= 6.1).
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)
def __init__(self, server, db=None, user=None, password=None,
transport=None, verbose=False):
self._set_services(server, transport, verbose)
self.reset()
self.context = None
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()
float_version = float(self.major_version)
# 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
self._searchargs = functools.partial(searchargs,
api_v9=(float_version < 10.0))
def _proxy_dispatch(self, name):
if self._server._api_v7:
return self._server.netsvc.ExportService.getService(name).dispatch
return functools.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 functools.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
``erppeek.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._environment = environment
client.login(user or conf_user, password=password, database=db)
return client
def reset(self):
self.user = self._environment = None
self._db, self._models = (), {}
self._execute = self._exec_workflow = None
def __repr__(self):
return "<Client '%s#%s'>" % (self._server, self._db)
def login(self, user, password=None, database=None):
"""Switch `user` and (optionally) `database`.
If the `password` is not available, it will be asked.
"""
if database:
try:
dbs = self.db.list()
except Fault:
pass # AccessDenied: simply ignore this check
else:
if database not in dbs:
raise Error("Database '%s' does not exist: %s" %
(database, dbs))
if not self._db:
self._db = database
# Used for logging, copied from odoo.sql_db.db_connect
current_thread().dbname = database
elif self._db:
database = self._db
else:
raise Error('Not connected')
(uid, password) = self._auth(database, user, password)
if not uid:
current_thread().dbname = self._db
raise Error('Invalid username or password')
if self._db != database:
self.reset()
self._db = database
self.user = user
# Authenticated endpoints
def authenticated(method):
return functools.partial(method, self._db, uid, password)
self._execute = authenticated(self._object.execute)
self._exec_workflow = authenticated(self._object.exec_workflow)
if self.major_version != '5.0':
# Only for Odoo and OpenERP >= 6
self.execute_kw = authenticated(self._object.execute_kw)
if self._report: # Odoo <= 10
self.report = authenticated(self._report.report)
self.report_get = authenticated(self._report.report_get)
if self.major_version != '5.0':
self.render_report = authenticated(self._report.render_report)
if self._wizard: # OpenERP <= 6.1
self._wizard_execute = authenticated(self._wizard.execute)
self._wizard_create = authenticated(self._wizard.create)
return uid
# Needed for interactive use
connect = None
_login = login
_login.cache = {}
def _check_valid(self, database, uid, password):
execute = self._object.execute
try:
execute(database, uid, password, 'res.users', 'fields_get_keys')
return True
except Fault:
return False
def _auth(self, database, user, password):
assert database
cache_key = (self._server, database, user)
if password:
# If password is explicit, call the 'login' method
uid = None
else:
# Read from cache
uid, password = self._login.cache.get(cache_key) or (None, None)
# Read from table 'res.users'
if ((not uid and self._db == database and
self.access('res.users', 'write'))):
obj = self.read('res.users',
[('login', '=', user)], 'id password')
if obj:
uid = obj[0]['id']
password = obj[0]['password']
else:
# Invalid user
uid = False
# Ask for password
if not password and uid is not False:
from getpass import getpass
password = getpass('Password for %r: ' % user)
if uid:
# Check if password changed
if not self._check_valid(database, uid, password):
if cache_key in self._login.cache:
del self._login.cache[cache_key]
uid = False
elif uid is None:
# Do a standard 'login'
uid = self.common.login(database, user, password)
if uid:
# Update the cache
self._login.cache[cache_key] = (uid, password)
return (uid, password)
@classmethod
def _set_interactive(cls, global_vars={}):
# Don't call multiple times
del Client._set_interactive
for name in ['__name__', '__doc__'] + __all__:
global_vars[name] = globals()[name]
def get_pool(db_name=None):
"""Return a model registry.
Use get_pool().cursor() to grab a cursor on an Odoo database.
With OpenERP, use get_pool().db.cursor() instead.
"""
client = global_vars['client']
return client._server._get_pool(db_name or client._db)
def connect(self, env=None):
"""Connect to another environment and replace the globals()."""
if env:
# Safety measure: turn down the previous connection
global_vars['client'].reset()
client = self.from_config(env, verbose=self.db._verbose)
return
client = self
env = client._environment or client._db
try: # copy the context to the new client
client.context = dict(global_vars['client'].context)
except (KeyError, TypeError):
pass # client not yet in globals(), or context is None
global_vars['client'] = client
if hasattr(client._server, 'modules'):
global_vars['get_pool'] = get_pool
# Tweak prompt
sys.ps1 = '%s >>> ' % (env,)
sys.ps2 = '%s ... ' % (env,)
# Logged in?
if client.user:
global_vars['model'] = client.model
global_vars['models'] = client.models
global_vars['do'] = client.execute
print('Logged in as %r' % (client.user,))
else:
global_vars.update({'model': None, 'models': None, 'do': None})
def login(self, user, password=None, database=None):
"""Switch `user` and (optionally) `database`."""
try:
self._login(user, password=password, database=database)
except Error as exc:
print('%s: %s' % (exc.__class__.__name__, exc))
else:
# Register the new globals()
self.connect()
# Set hooks to recreate the globals()
cls.login = login
cls.connect = connect
return global_vars
def create_database(self, passwd, database, demo=False, lang='en_US',
user_password='admin', login='admin',
country_code=None):
"""Create a new database.
The superadmin `passwd` and the `database` name are mandatory.
By default, `demo` data are not loaded, `lang` is ``en_US``
and no country is set into the database.
Login if successful.
"""
float_version = float(self.major_version)
customize = (login != 'admin' or country_code)
if customize and float_version < 9.0:
raise Error("Custom 'login' and 'country_code' are not supported")
if float_version < 6.1:
thread_id = self.db.create(passwd, database, demo, lang,
user_password)
progress = 0
try:
while progress < 1:
time.sleep(3)
progress, users = self.db.get_progress(passwd, thread_id)
except KeyboardInterrupt:
return {'id': thread_id, 'progress': progress}
elif not customize:
self.db.create_database(passwd, database, demo, lang,
user_password)
else:
self.db.create_database(passwd, database, demo, lang,
user_password, login, country_code)
return self.login(login, user_password, database=database)
def clone_database(self, passwd, db_name):
"""Clone the current database.
The superadmin `passwd` and `db_name` are mandatory.
Login if successful.
Supported since OpenERP 7.
"""
self.db.duplicate_database(passwd, self._db, db_name)
# Login with the current user into the new database
(uid, password) = self._auth(self._db, self.user, None)
return self.login(self.user, password, database=db_name)
def execute(self, obj, method, *params, **kwargs):
"""Wrapper around ``object.execute`` 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.user, 'Not connected'
assert isinstance(obj, basestring)
assert isinstance(method, basestring) and method != 'browse'
context = kwargs.pop('context', None)
ordered = single_id = False
if method == 'read':
assert params, 'Missing parameter'
if not (params[0] and isinstance(params[0], list)):
single_id = True
ids = [params[0]] if params[0] else False
elif issearchdomain(params[0]):
# Combine search+read
search_params = self._searchargs(params[:1], kwargs, context)
ordered = len(search_params) > 3 and search_params[3]
ids = self._execute(obj, 'search', *search_params)
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
if len(params) > 1:
params = (ids,) + params[1:]
else:
params = (ids, kwargs.pop('fields', None))
elif method == 'search':
# Accept keyword arguments for the search method
params = self._searchargs(params, kwargs, context)
context = None
elif method == 'search_count':
params = self._searchargs(params)
elif method == 'perm_read':
# broken with a single id (verified with 5.0 and 6.1)
if params and isinstance(params[0], int_types):
params = ([params[0]],) + params[1:]
if context:
params = params + (context,)
# Ignore extra keyword arguments
for item in kwargs.items():
print('Ignoring: %s = %r' % item)
res = self._execute(obj, method, *params)
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 exec_workflow(self, obj, signal, obj_id):
"""Wrapper around ``object.exec_workflow`` RPC method.
Argument `obj` is the name of the model. The `signal`
is sent to the object identified by its integer ``id`` `obj_id`.
"""
assert self.user, 'Not connected'
assert isinstance(obj, basestring) and isinstance(signal, basestring)
return self._exec_workflow(obj, signal, obj_id)
def wizard(self, name, datas=None, action='init', context=_DEFAULT):
"""Wrapper around ``wizard.create`` and ``wizard.execute``
RPC methods.
If only `name` is provided, a new wizard is created and its ``id`` is
returned. If `action` is not ``"init"``, then the action is executed.
In this case the `name` is either an ``id`` or a string.
If the `name` is a string, the wizard is created before the execution.
The optional `datas` argument provides data for the action.
The optional `context` argument is passed to the RPC method.
Removed in OpenERP 7.
"""
if isinstance(name, int_types):
wiz_id = name
else:
wiz_id = self._wizard_create(name)
if datas is None:
if action == 'init' and name != wiz_id:
return wiz_id
datas = {}
if context is _DEFAULT:
context = self.context
return self._wizard_execute(wiz_id, datas, action, context)
def _upgrade(self, modules, button):
# First, update the list of modules
ir_module = self.model('ir.module.module', False)
updated, added = ir_module.update_list()
if added:
print('%s module(s) added to the list' % added)
# Find modules
ids = modules and ir_module.search([('name', 'in', modules)])
if ids:
# 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', 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
ir_module.write(ids, {'state': 'to remove'})
try:
# Click upgrade/install/uninstall button
self.execute('ir.module.module', button, ids)
except Exception:
if button == 'button_uninstall':
ir_module.write(ids, {'state': 'installed'})
raise
mods = ir_module.read([_pending_state], 'name state')
if not mods:
if ids:
print('Already up-to-date: %s' %
self.modules([('id', 'in', 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(ids))
print('%s module(s) to process:' % len(mods))
for mod in mods:
print(' %(state)s\t%(name)s' % mod)
# Empty the models' cache
self._models.clear()
# Apply scheduled upgrades
if self.major_version == '5.0':
# Wizard "Apply Scheduled Upgrades"
rv = self.wizard('module.upgrade', action='start')
if 'config' not in [state[0] for state in rv.get('state', ())]:
# Something bad happened
return rv
else:
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')
def search(self, obj, *params, **kwargs):
"""Filter the records in the `domain`, return the ``ids``."""
return self.execute(obj, 'search', *params, **kwargs)
def count(self, obj, domain=None):
"""Count the records in the `domain`."""
return self.execute(obj, 'search_count', domain or [])
def read(self, obj, *params, **kwargs):
"""Wrapper for ``client.execute(obj, 'read', [...], ('a', 'b'))``.
The first argument `obj` is the model name (example: ``"res.partner"``)
The second argument, `domain`, accepts:
- ``[('name', '=', 'mushroom'), ('state', '!=', 'draft')]``
- ``['name = mushroom', 'state != draft']``
- ``[]``
- a list of ids ``[1, 2, 3]`` or a single id ``42``
The third argument, `fields`, accepts:
- a single field: ``'first_name'``
- a tuple of fields: ``('street', 'city')``
- a space separated string: ``'street city'``
- a format spec: ``'%(street)s %(city)s'``
If `fields` is omitted, all fields are read.
If `domain` is a single id, then:
- return a single value if a single field is requested.
- return a string if a format spec is passed in the `fields` argument.
- else, return a dictionary.
If `domain` is not a single id, the returned value is a list of items.
Each item complies with the rules of the previous paragraph.
The optional keyword arguments `offset`, `limit` and `order` are
used to restrict the search. The `order` is also used to order the
results returned. Note: the low-level RPC method ``read`` itself does
not preserve the order of the results.
"""
fmt = None
if len(params) > 1 and isinstance(params[1], basestring):
fmt = ('%(' in params[1]) and params[1]
if fmt:
fields = _fields_re.findall(fmt)
else:
# transform: "zip city" --> ("zip", "city")
fields = params[1].split()
if len(fields) == 1:
fmt = () # marker
params = (params[0], fields) + params[2:]
res = self.execute(obj, 'read', *params, **kwargs)
if not res:
return res
if fmt:
if isinstance(res, list):
return [(d and fmt % d) for d in res]
return fmt % res
if fmt == ():
if isinstance(res, list):