forked from tinyerp/erppeek
-
Notifications
You must be signed in to change notification settings - Fork 0
/
erppeek.py
1708 lines (1485 loc) · 64 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 atexit
import csv
import functools
import optparse
import os
import re
import shlex
import sys
import time
import traceback
import _ast
try:
from ptpython.repl import embed
PTPYTHON = True
except ImportError:
PTPYTHON = False
try: # Python 3
import configparser
from threading import current_thread
from xmlrpc.client import Fault, ServerProxy, MININT, MAXINT
PY2 = False
except ImportError: # Python 2
import ConfigParser as configparser
from threading import currentThread as current_thread
from xmlrpclib import Fault, ServerProxy, MININT, MAXINT
PY2 = True
__version__ = '1.6.3'
__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'
DEFAULT_DB = 'openerp'
DEFAULT_USER = 'admin'
MAXCOL = [79, 179, 9999] # Line length in verbose mode
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(
'([\w._]+)\s*' '(=(?:like|ilike|\?)|[<>]=?|!?=(?!=)'
'|(?<= )(?:like|ilike|in|not like|not ilike|not in|child_of))' '\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'],
}
# 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 writeheader(self):
# Method 'writeheader' does not exist in Python 2.6
header = dict(zip(self.fieldnames, self.fieldnames))
self.writerow(header)
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
# Simplified ast.literal_eval which does not parse operators
def _convert(node, _consts={'None': None, 'True': True, 'False': False}):
if isinstance(node, _ast.Str):
return node.s
if isinstance(node, _ast.Num):
return node.n
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 dict([(_convert(k), _convert(v))
for (k, v) in zip(node.keys, node.values)])
if hasattr(node, 'value') and str(node.value) in _consts:
return node.value # Python 3.4+
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.
If `chain` is True, then the original exception is printed too.
"""
values = _format_exception(exc_type, exc, tb, limit=limit)
if issubclass(exc_type, Error):
values = [str(exc) + '\n']
elif ((issubclass(exc_type, Fault) and
isinstance(exc.faultCode, basestring))):
# Format readable 'Fault' errors
(etype, __, msg) = exc.faultCode.partition('--')
server_tb = None
if etype.strip() != 'warning':
msg = exc.faultCode
if not msg.startswith('FATAL:'):
server_tb = exc.faultString
fault = '%s: %s\n' % (exc_type.__name__, msg.strip())
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``, ``user`` 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.SafeConfigParser()
with open(Client._config_file) as f:
p.readfp(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:
server = '%s://%s:%s' % (scheme, env['host'], env['port'])
return (server, env['database'], env['username'], env.get('password'))
def start_odoo_services(options=None, appname=None):
"""Initialize the Odoo services.
Import the ``openerp`` package and load the Odoo services.
The argument `options` receives the command line arguments
for ``openerp``. Example:
``['-c', '/path/to/openerp-server.conf', '--without-demo', 'all']``.
Return the ``openerp`` package.
"""
import openerp as 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
try:
odoo.api.Environment._local.environments = \
odoo.api.Environments()
except AttributeError:
pass
def close_all():
for db in odoo.modules.registry.RegistryManager.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):
"""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)
if (kwargs or context) and len(params) == 1:
params = (domain,
kwargs.pop('offset', 0),
kwargs.pop('limit', None),
kwargs.pop('order', None),
context)
else:
params = (domain,) + params[1:]
return params
class Error(Exception):
"""An ERPpeek error."""
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 ``openerp`` module, 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.
"""
_rpcpath = ''
_methods = ()
def __init__(self, server, endpoint, methods,
transport=None, verbose=False):
if isinstance(server, basestring):
self._rpcpath = rpcpath = server + '/xmlrpc/'
proxy = ServerProxy(rpcpath + endpoint,
transport=transport, allow_none=True)
if hasattr(proxy._ServerProxy__transport, 'close'): # >= 2.7
self.close = proxy._ServerProxy__transport.close
rpc = proxy._ServerProxy__request
elif server._api_v7:
rpc = server.netsvc.ExportService.getService(endpoint).dispatch
else: # Odoo v8
rpc = functools.partial(server.http.dispatch_rpc, endpoint)
self._dispatch = rpc
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 ``openerp`` module, 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):
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
float_version = 99.0
def get_proxy(name):
methods = list(_methods[name]) if (name in _methods) else []
if float_version < 8.0:
methods += _obsolete_methods.get(name) or ()
return Service(server, name, methods, transport, verbose=verbose)
self.server_version = ver = get_proxy('db').server_version()
self.major_version = re.match('\d+\.?\d*', ver).group()
float_version = float(self.major_version)
# Create the XML-RPC proxies
self.db = get_proxy('db')
self.common = get_proxy('common')
self._object = get_proxy('object')
self._report = get_proxy('report')
self._wizard = get_proxy('wizard') if float_version < 7.0 else None
self.reset()
self.context = None
if db:
# Try to login
self.login(user, password=password, database=db)
@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 or '', 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 openerp.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)
self.report = authenticated(self._report.report)
self.report_get = authenticated(self._report.report_get)
if self.major_version != '5.0':
# Only for Odoo and OpenERP >= 6
self.execute_kw = authenticated(self._object.execute_kw)
self.render_report = authenticated(self._report.render_report)
if self._wizard:
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(db_name).db.cursor() to grab a cursor.
With Odoo v8, use get_pool(db_name).cursor() instead.
"""
client = global_vars['client']
registry = client._server.modules.registry
return registry.RegistryManager.get(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'):
"""Create a new database.
The superadmin `passwd` and the `database` name are mandatory.
By default, `demo` data are not loaded and `lang` is ``en_US``.
Wait for the thread to finish and login if successful.
"""
if self.major_version in ('5.0', '6.0'):
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}
else:
self.db.create_database(passwd, database, demo, lang,
user_password)
return self.login('admin', user_password, database=database)
def duplicate_database(self, passwd, db_original_name, db_name,
user_password='admin'):
"""Duplicate an existing database.
The superadmin `passwd`, `db_original_name` and `db_name` are
mandatory.
Wait for the thread to finish and login if successful.
"""
self.db.duplicate_database(passwd, db_original_name, db_name)
return self.login('admin', 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
if issearchdomain(params[0]):
# Combine search+read
search_params = searchargs(params[:1], kwargs, context)
ordered = len(search_params) > 3 and search_params[3]
ids = self._execute(obj, 'search', *search_params)
elif isinstance(params[0], list):
ordered = kwargs.pop('order', False) and params[0]
ids = set(params[0])
ids.discard(False)
if not ids and ordered:
return [False] * len(ordered)
ids = sorted(ids)
else:
single_id = True
ids = [params[0]] if params[0] else False
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 = searchargs(params, kwargs, context)
context = None
elif method == 'search_count':
params = 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 = dict([(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=None):
"""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 None:
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 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'], '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):
return [(d and d[fields[0]]) for d in res]
return res[fields[0]]
return res
def _models_get(self, name):
try:
return self._models[name]
except KeyError:
self._models[name] = m = Model._new(self, name)
return m
def models(self, name=''):
"""Return a dictionary of models.
The argument `name` is a pattern to filter the models returned.
If omitted, all models are returned.
Keys are camel case names of the models.
Values are instances of :class:`Model`.
The return value can be used to declare the models in the global
namespace:
>>> globals().update(client.models('res.'))
"""
domain = [('model', 'like', name)]
models = self.execute('ir.model', 'read', domain, ('model',))
names = [m['model'] for m in models]
return dict([(mixedcase(mod), self._models_get(mod)) for mod in names])
def model(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[name] if check else self._models_get(name)
except KeyError:
models = self.models(name)
if name in self._models:
return self._models[name]
if models:
errmsg = 'Model not found. These models exist:'
else:
errmsg = 'Model not found: %s' % (name,)
raise Error('\n * '.join([errmsg] + [str(m) for m in models.values()]))
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']))
mods = self.read('ir.module.module', 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 keys(self, obj):
"""Wrapper for :meth:`Model.keys` method."""
return self.model(obj).keys()
def fields(self, obj, names=None):
"""Wrapper for :meth:`Model.fields` method."""
return self.model(obj).fields(names=names)
def field(self, obj, name):
"""Wrapper for :meth:`Model.field` method."""
return self.model(obj).field(name)
def access(self, obj, mode='read'):
"""Wrapper for :meth:`Model.access` method."""
try:
self._execute('ir.model.access', 'check', obj, mode)
return True
except (TypeError, Fault):
return False
def __getattr__(self, method):
if not method.islower():
return _memoize(self, method, self.model(lowercase(method)))