Debian Codegraph @

odoorpc/models.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright 2014 Sébastien Alix
3 # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl)
4 """Provide the :class:`Model` class which allow to access dynamically to all
5 methods proposed by a data model.
6 """
7
8 __all__ = ['Model']
9
10 import sys
11
12 from odoorpc import error
13
14 # Python 2
15 if sys.version_info[0] < 3:
16 # noqa: F821
17 NORMALIZED_TYPES = (int, long, str, unicode) # noqa: F821
18 # Python >= 3
19 else:
20 NORMALIZED_TYPES = (int, str, bytes)
21
22
23 FIELDS_RESERVED = ['id', 'ids', '__odoo__', '__osv__', '__data__', 'env']
24
25
26 def _normalize_ids(ids):
27 """Normalizes the ids argument for ``browse``."""
28 if not ids:
29 return []
30 if ids.__class__ in NORMALIZED_TYPES:
31 return [ids]
32 return list(ids)
33
34
35 class IncrementalRecords(object):
36 """A helper class used internally by __iadd__ and __isub__ methods.
37 Afterwards, field descriptors can adapt their behaviour when an instance of
38 this class is set.
39 """
40
41 def __init__(self, tuples):
42 self.tuples = tuples
43
44
45 class MetaModel(type):
46 """Define class methods for the :class:`Model` class."""
47
48 _env = None
49
50 def __getattr__(cls, method):
51 """Provide a dynamic access to a RPC method."""
52 if method.startswith('_'):
53 return super(MetaModel, cls).__getattr__(method)
54
55 def rpc_method(*args, **kwargs):
56 """Return the result of the RPC request."""
57 if cls._odoo.config['auto_context'] and 'context' not in kwargs:
58 kwargs['context'] = cls.env.context
59 result = cls._odoo.execute_kw(cls._name, method, args, kwargs)
60 return result
61
62 return rpc_method
63
64 def __repr__(cls):
65 return "Model(%r)" % (cls._name)
66
67 @property
68 def env(cls):
69 """The environment used for this model/recordset."""
70 return cls._env
71
72
73 # An intermediate class used to associate the 'MetaModel' metaclass to the
74 # 'Model' one with a Python 2 and Python 3 compatibility
75 BaseModel = MetaModel('BaseModel', (), {})
76
77
78 class Model(BaseModel):
79 """Base class for all data model proxies.
80
81 .. note::
82 All model proxies (based on this class) are generated by an
83 :class:`environment <odoorpc.env.Environment>`
84 (see the :attr:`odoorpc.ODOO.env` property).
85
86 .. doctest::
87 :options: +SKIP
88
89 >>> import odoorpc
90 >>> odoo = odoorpc.ODOO('localhost', port=8069)
91 >>> odoo.login('db_name', 'admin', 'password')
92 >>> User = odoo.env['res.users']
93 >>> User
94 Model('res.users')
95
96 .. doctest::
97 :hide:
98
99 >>> import odoorpc
100 >>> odoo = odoorpc.ODOO(HOST, protocol=PROTOCOL, port=PORT)
101 >>> odoo.login(DB, USER, PWD)
102 >>> User = odoo.env['res.users']
103 >>> User
104 Model('res.users')
105
106 Use this data model proxy to call any method:
107
108 .. doctest::
109 :options: +SKIP
110
111 >>> User.name_get([2]) # Use any methods from the model class
112 [[1, 'Mitchell Admin']]
113
114 .. doctest::
115 :hide:
116
117 >>> from odoorpc.tools import v
118 >>> uid = 1
119 >>> if v(VERSION) >= v('12.0'):
120 ... uid = 2
121 >>> data = User.name_get([uid])
122 >>> 'Admin' in data[0][1]
123 True
124
125 Get a recordset:
126
127 .. doctest::
128 :options: +SKIP
129
130 >>> user = User.browse(2)
131 >>> user.name
132 'Mitchell Admin'
133
134 .. doctest::
135 :hide:
136
137 >>> from odoorpc.tools import v
138 >>> uid = 1
139 >>> if v(VERSION) >= v('12.0'):
140 ... uid = 2
141 >>> user = User.browse(uid)
142 >>> 'Admin' in user.name
143 True
144
145 And call any method from it, it will be automatically applied on the
146 current record:
147
148 .. doctest::
149 :options: +SKIP
150
151 >>> user.name_get() # No IDs in parameter, the method is applied on the current recordset
152 [[1, 'Mitchell Admin']]
153
154
155 .. doctest::
156 :hide:
157
158 >>> data = user.name_get()
159 >>> 'Admin' in data[0][1]
160 True
161
162 .. warning::
163
164 Excepted the :func:`browse <odoorpc.models.Model.browse>` method,
165 method calls are purely dynamic. As long as you know the signature of
166 the model method targeted, you will be able to use it
167 (see the :ref:`tutorial <tuto-execute-queries>`).
168
169 """
170
171 __metaclass__ = MetaModel
172 _odoo = None
173 _name = None
174 _columns = {} # {field: field object}
175
176 def __init__(self):
177 super(Model, self).__init__()
178 self._env_local = None
179 self._from_record = None
180 self._ids = []
181 self._values = {} # {field: {ID: value}}
182 self._values_to_write = {} # {field: {ID: value}}
183 for field in self._columns:
184 self._values[field] = {}
185 self._values_to_write[field] = {}
186 self.with_context = self._with_context
187 self.with_env = self._with_env
188
189 @property
190 def env(self):
191 """The environment used for this model/recordset."""
192 if self._env_local:
193 return self._env_local
194 return self.__class__._env
195
196 @property
197 def id(self):
198 """ID of the record (or the first ID of a recordset)."""
199 return self._ids[0] if self._ids else None
200
201 @property
202 def ids(self):
203 """IDs of the recorset."""
204 return self._ids
205
206 @classmethod
207 def _browse(cls, env, ids, from_record=None, iterated=None):
208 """Create an instance (a recordset) corresponding to `ids` and
209 attached to `env`.
210
211 `from_record` parameter is used when the recordset is related to a
212 parent record, and as such can take the value of a tuple
213 (record, field). This is useful to update the parent record when the
214 current recordset is modified.
215
216 `iterated` can take the value of an iterated recordset, and no extra
217 RPC queries are made to generate the resulting record (recordset and
218 its record share the same values).
219 """
220 records = cls()
221 records._env_local = env
222 records._ids = _normalize_ids(ids)
223 if iterated:
224 records._values = iterated._values
225 records._values_to_write = iterated._values_to_write
226 else:
227 records._from_record = from_record
228 records._values = {}
229 records._values_to_write = {}
230 for field in cls._columns:
231 records._values[field] = {}
232 records._values_to_write[field] = {}
233 records._init_values()
234 return records
235
236 @classmethod
237 def browse(cls, ids):
238 """Browse one or several records (if `ids` is a list of IDs).
239
240 .. doctest::
241
242 >>> odoo.env['res.partner'].browse(1)
243 Recordset('res.partner', [1])
244
245 .. doctest::
246 :options: +SKIP
247
248 >>> [partner.name for partner in odoo.env['res.partner'].browse([1, 3])]
249 ['YourCompany', 'Mitchell Admin']
250
251 .. doctest::
252 :hide:
253
254 >>> names = [partner.name for partner in odoo.env['res.partner'].browse([1, 3])]
255 >>> 'YourCompany' in names[0]
256 True
257 >>> 'Admin' in names[1]
258 True
259
260 A list of data types returned by such record fields are
261 available :ref:`here <fields>`.
262
263 :return: a :class:`Model <odoorpc.models.Model>`
264 instance (recordset)
265 :raise: :class:`odoorpc.error.RPCError`
266 """
267 return cls._browse(cls.env, ids)
268
269 @classmethod
270 def with_context(cls, *args, **kwargs):
271 """Return a model (or recordset) equivalent to the current model
272 (or recordset) attached to an environment with another context.
273 The context is taken from the current environment or from the
274 positional arguments `args` if given, and modified by `kwargs`.
275
276 Thus, the following two examples are equivalent:
277
278 .. doctest::
279
280 >>> Product = odoo.env['product.product']
281 >>> Product.with_context(lang='fr_FR')
282 Model('product.product')
283
284 .. doctest::
285
286 >>> context = Product.env.context
287 >>> Product.with_context(context, lang='fr_FR')
288 Model('product.product')
289
290 This method is very convenient for example to search records
291 whatever their active status are (active/inactive):
292
293 .. doctest::
294
295 >>> all_product_ids = Product.with_context(active_test=False).search([])
296
297 Or to update translations of a recordset:
298
299 .. doctest::
300
301 >>> product_en = Product.browse(1)
302 >>> product_en.env.lang
303 'en_US'
304 >>> product_en.name = "My product" # Update the english translation
305 >>> product_fr = product_en.with_context(lang='fr_FR')
306 >>> product_fr.env.lang
307 'fr_FR'
308 >>> product_fr.name = "Mon produit" # Update the french translation
309 """
310 context = dict(args[0] if args else cls.env.context, **kwargs)
311 return cls.with_env(cls.env(context=context))
312
313 def _with_context(self, *args, **kwargs):
314 """As the `with_context` class method but for recordset."""
315 context = dict(args[0] if args else self.env.context, **kwargs)
316 return self.with_env(self.env(context=context))
317
318 @classmethod
319 def with_env(cls, env):
320 """Return a model (or recordset) equivalent to the current model
321 (or recordset) attached to `env`.
322 """
323 new_cls = type(cls.__name__, cls.__bases__, dict(cls.__dict__))
324 new_cls._env = env
325 return new_cls
326
327 def _with_env(self, env):
328 """As the `with_env` class method but for recordset."""
329 res = self._browse(env, self._ids)
330 return res
331
332 def _init_values(self, context=None):
333 """Retrieve field values from the server.
334 May be used to restore the original values in the purpose to cancel
335 all changes made.
336 """
337 if context is None:
338 context = self.env.context
339 # Get basic fields (no relational ones)
340 basic_fields = []
341 for field_name in self._columns:
342 field = self._columns[field_name]
343 if not getattr(field, 'relation', False):
344 basic_fields.append(field_name)
345 # Fetch values from the server
346 if self.ids:
347 rows = self.__class__.read(
348 self.ids, basic_fields, context=context, load='_classic_write'
349 )
350 ids_fetched = set()
351 for row in rows:
352 ids_fetched.add(row['id'])
353 for field_name in row:
354 if field_name == 'id':
355 continue
356 self._values[field_name][row['id']] = row[field_name]
357 ids_in_error = set(self.ids) - ids_fetched
358 if ids_in_error:
359 raise ValueError(
360 "There is no '{model}' record with IDs {ids}.".format(
361 model=self._name, ids=list(ids_in_error)
362 )
363 )
364 # No ID: fields filled with default values
365 else:
366 default_get = self.__class__.default_get(
367 list(self._columns), context=context
368 )
369 for field_name in self._columns:
370 self._values[field_name][None] = default_get.get(
371 field_name, False
372 )
373
374 def __getattr__(self, method):
375 """Provide a dynamic access to a RPC *instance* method (which applies
376 on the current recordset).
377
378 .. doctest::
379
380 >>> Partner = odoo.env['res.partner']
381 >>> Partner.write([1], {'name': 'YourCompany'}) # Class method
382 True
383 >>> partner = Partner.browse(1)
384 >>> partner.write({'name': 'YourCompany'}) # Instance method
385 True
386
387 """
388 if method.startswith('_'):
389 return super(Model, self).__getattr__(method)
390
391 def rpc_method(*args, **kwargs):
392 """Return the result of the RPC request."""
393 args = tuple([self.ids]) + args
394 if self._odoo.config['auto_context'] and 'context' not in kwargs:
395 kwargs['context'] = self.env.context
396 result = self._odoo.execute_kw(self._name, method, args, kwargs)
397 return result
398
399 return rpc_method
400
401 def __getitem__(self, key):
402 """If `key` is an integer or a slice, return the corresponding record
403 selection as a recordset.
404 """
405 if isinstance(key, int) or isinstance(key, slice):
406 return self._browse(self.env, self._ids[key], iterated=self)
407 else:
408 return getattr(self, key)
409
410 def __int__(self):
411 return self.id
412
413 def __eq__(self, other):
414 return other.__class__ == self.__class__ and self.id == other.id
415
416 # Need to explicitly declare '__hash__' in Python 3
417 # (because '__eq__' is defined)
418 __hash__ = BaseModel.__hash__
419
420 def __ne__(self, other):
421 return other.__class__ != self.__class__ or self.id != other.id
422
423 def __repr__(self):
424 return "Recordset({!r}, {})".format(self._name, self.ids)
425
426 def __iter__(self):
427 """Return an iterator over `self`."""
428 for id_ in self._ids:
429 yield self._browse(self.env, id_, iterated=self)
430
431 def __nonzero__(self):
432 return bool(getattr(self, '_ids', True))
433
434 def __len__(self):
435 return len(self.ids)
436
437 def __iadd__(self, records):
438 if not self._from_record:
439 raise error.InternalError("No parent record to update")
440 try:
441 list(records)
442 except TypeError:
443 records = [records]
444 parent = self._from_record[0]
445 field = self._from_record[1]
446 updated_values = parent._values_to_write[field.name]
447 values = []
448 if updated_values.get(parent.id):
449 values = updated_values[parent.id][:] # Copy
450 from odoorpc import fields
451
452 for id_ in fields.records2ids(records):
453 if (3, id_) in values:
454 values.remove((3, id_))
455 if (4, id_) not in values:
456 values.append((4, id_))
457 return IncrementalRecords(values)
458
459 def __isub__(self, records):
460 if not self._from_record:
461 raise error.InternalError("No parent record to update")
462 try:
463 list(records)
464 except TypeError:
465 records = [records]
466 parent = self._from_record[0]
467 field = self._from_record[1]
468 updated_values = parent._values_to_write[field.name]
469 values = []
470 if updated_values.get(parent.id):
471 values = updated_values[parent.id][:] # Copy
472 from odoorpc import fields
473
474 for id_ in fields.records2ids(records):
475 if (4, id_) in values:
476 values.remove((4, id_))
477 if (3, id_) not in values:
478 values.append((3, id_))
479 return values