File: models.py

package info (click to toggle)
python-odoorpc 0.10.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 604 kB
  • sloc: python: 3,461; makefile: 154; sh: 36
file content (479 lines) | stat: -rw-r--r-- 15,034 bytes parent folder | download | duplicates (2)
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
# -*- coding: utf-8 -*-
# Copyright 2014 Sébastien Alix
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl)
"""Provide the :class:`Model` class which allow to access dynamically to all
methods proposed by a data model.
"""

__all__ = ['Model']

import sys

from odoorpc import error

# Python 2
if sys.version_info[0] < 3:
    # noqa: F821
    NORMALIZED_TYPES = (int, long, str, unicode)  # noqa: F821
# Python >= 3
else:
    NORMALIZED_TYPES = (int, str, bytes)


FIELDS_RESERVED = ['id', 'ids', '__odoo__', '__osv__', '__data__', 'env']


def _normalize_ids(ids):
    """Normalizes the ids argument for ``browse``."""
    if not ids:
        return []
    if ids.__class__ in NORMALIZED_TYPES:
        return [ids]
    return list(ids)


class IncrementalRecords(object):
    """A helper class used internally by __iadd__ and __isub__ methods.
    Afterwards, field descriptors can adapt their behaviour when an instance of
    this class is set.
    """

    def __init__(self, tuples):
        self.tuples = tuples


class MetaModel(type):
    """Define class methods for the :class:`Model` class."""

    _env = None

    def __getattr__(cls, method):
        """Provide a dynamic access to a RPC method."""
        if method.startswith('_'):
            return super(MetaModel, cls).__getattr__(method)

        def rpc_method(*args, **kwargs):
            """Return the result of the RPC request."""
            if cls._odoo.config['auto_context'] and 'context' not in kwargs:
                kwargs['context'] = cls.env.context
            result = cls._odoo.execute_kw(cls._name, method, args, kwargs)
            return result

        return rpc_method

    def __repr__(cls):
        return "Model(%r)" % (cls._name)

    @property
    def env(cls):
        """The environment used for this model/recordset."""
        return cls._env


# An intermediate class used to associate the 'MetaModel' metaclass to the
# 'Model' one with a Python 2 and Python 3 compatibility
BaseModel = MetaModel('BaseModel', (), {})


class Model(BaseModel):
    """Base class for all data model proxies.

    .. note::
        All model proxies (based on this class) are generated by an
        :class:`environment <odoorpc.env.Environment>`
        (see the :attr:`odoorpc.ODOO.env` property).

    .. doctest::
        :options: +SKIP

        >>> import odoorpc
        >>> odoo = odoorpc.ODOO('localhost', port=8069)
        >>> odoo.login('db_name', 'admin', 'password')
        >>> User = odoo.env['res.users']
        >>> User
        Model('res.users')

    .. doctest::
        :hide:

        >>> import odoorpc
        >>> odoo = odoorpc.ODOO(HOST, protocol=PROTOCOL, port=PORT)
        >>> odoo.login(DB, USER, PWD)
        >>> User = odoo.env['res.users']
        >>> User
        Model('res.users')

    Use this data model proxy to call any method:

    .. doctest::
        :options: +SKIP

        >>> User.name_get([2])  # Use any methods from the model class
        [[1, 'Mitchell Admin']]

    .. doctest::
        :hide:

        >>> from odoorpc.tools import v
        >>> uid = 1
        >>> if v(VERSION) >= v('12.0'):
        ...     uid = 2
        >>> data = User.name_get([uid])
        >>> 'Admin' in data[0][1]
        True

    Get a recordset:

    .. doctest::
        :options: +SKIP

        >>> user = User.browse(2)
        >>> user.name
        'Mitchell Admin'

    .. doctest::
        :hide:

        >>> from odoorpc.tools import v
        >>> uid = 1
        >>> if v(VERSION) >= v('12.0'):
        ...     uid = 2
        >>> user = User.browse(uid)
        >>> 'Admin' in user.name
        True

    And call any method from it, it will be automatically applied on the
    current record:

    .. doctest::
        :options: +SKIP

        >>> user.name_get()     # No IDs in parameter, the method is applied on the current recordset
        [[1, 'Mitchell Admin']]


    .. doctest::
        :hide:

        >>> data = user.name_get()
        >>> 'Admin' in data[0][1]
        True

    .. warning::

        Excepted the :func:`browse <odoorpc.models.Model.browse>` method,
        method calls are purely dynamic. As long as you know the signature of
        the model method targeted, you will be able to use it
        (see the :ref:`tutorial <tuto-execute-queries>`).

    """

    __metaclass__ = MetaModel
    _odoo = None
    _name = None
    _columns = {}  # {field: field object}

    def __init__(self):
        super(Model, self).__init__()
        self._env_local = None
        self._from_record = None
        self._ids = []
        self._values = {}  # {field: {ID: value}}
        self._values_to_write = {}  # {field: {ID: value}}
        for field in self._columns:
            self._values[field] = {}
            self._values_to_write[field] = {}
        self.with_context = self._with_context
        self.with_env = self._with_env

    @property
    def env(self):
        """The environment used for this model/recordset."""
        if self._env_local:
            return self._env_local
        return self.__class__._env

    @property
    def id(self):
        """ID of the record (or the first ID of a recordset)."""
        return self._ids[0] if self._ids else None

    @property
    def ids(self):
        """IDs of the recorset."""
        return self._ids

    @classmethod
    def _browse(cls, env, ids, from_record=None, iterated=None):
        """Create an instance (a recordset) corresponding to `ids` and
        attached to `env`.

        `from_record` parameter is used when the recordset is related to a
        parent record, and as such can take the value of a tuple
        (record, field). This is useful to update the parent record when the
        current recordset is modified.

        `iterated` can take the value of an iterated recordset, and no extra
        RPC queries are made to generate the resulting record (recordset and
        its record share the same values).
        """
        records = cls()
        records._env_local = env
        records._ids = _normalize_ids(ids)
        if iterated:
            records._values = iterated._values
            records._values_to_write = iterated._values_to_write
        else:
            records._from_record = from_record
            records._values = {}
            records._values_to_write = {}
            for field in cls._columns:
                records._values[field] = {}
                records._values_to_write[field] = {}
            records._init_values()
        return records

    @classmethod
    def browse(cls, ids):
        """Browse one or several records (if `ids` is a list of IDs).

        .. doctest::

            >>> odoo.env['res.partner'].browse(1)
            Recordset('res.partner', [1])

        .. doctest::
            :options: +SKIP

            >>> [partner.name for partner in odoo.env['res.partner'].browse([1, 3])]
            ['YourCompany', 'Mitchell Admin']

        .. doctest::
            :hide:

            >>> names = [partner.name for partner in odoo.env['res.partner'].browse([1, 3])]
            >>> 'YourCompany' in names[0]
            True
            >>> 'Admin' in names[1]
            True

        A list of data types returned by such record fields are
        available :ref:`here <fields>`.

        :return: a :class:`Model <odoorpc.models.Model>`
            instance (recordset)
        :raise: :class:`odoorpc.error.RPCError`
        """
        return cls._browse(cls.env, ids)

    @classmethod
    def with_context(cls, *args, **kwargs):
        """Return a model (or recordset) equivalent to the current model
        (or recordset) attached to an environment with another context.
        The context is taken from the current environment or from the
        positional arguments `args` if given, and modified by `kwargs`.

        Thus, the following two examples are equivalent:

        .. doctest::

            >>> Product = odoo.env['product.product']
            >>> Product.with_context(lang='fr_FR')
            Model('product.product')

        .. doctest::

            >>> context = Product.env.context
            >>> Product.with_context(context, lang='fr_FR')
            Model('product.product')

        This method is very convenient for example to search records
        whatever their active status are (active/inactive):

        .. doctest::

            >>> all_product_ids = Product.with_context(active_test=False).search([])

        Or to update translations of a recordset:

        .. doctest::

            >>> product_en = Product.browse(1)
            >>> product_en.env.lang
            'en_US'
            >>> product_en.name = "My product"  # Update the english translation
            >>> product_fr = product_en.with_context(lang='fr_FR')
            >>> product_fr.env.lang
            'fr_FR'
            >>> product_fr.name = "Mon produit" # Update the french translation
        """
        context = dict(args[0] if args else cls.env.context, **kwargs)
        return cls.with_env(cls.env(context=context))

    def _with_context(self, *args, **kwargs):
        """As the `with_context` class method but for recordset."""
        context = dict(args[0] if args else self.env.context, **kwargs)
        return self.with_env(self.env(context=context))

    @classmethod
    def with_env(cls, env):
        """Return a model (or recordset) equivalent to the current model
        (or recordset) attached to `env`.
        """
        new_cls = type(cls.__name__, cls.__bases__, dict(cls.__dict__))
        new_cls._env = env
        return new_cls

    def _with_env(self, env):
        """As the `with_env` class method but for recordset."""
        res = self._browse(env, self._ids)
        return res

    def _init_values(self, context=None):
        """Retrieve field values from the server.
        May be used to restore the original values in the purpose to cancel
        all changes made.
        """
        if context is None:
            context = self.env.context
        # Get basic fields (no relational ones)
        basic_fields = []
        for field_name in self._columns:
            field = self._columns[field_name]
            if not getattr(field, 'relation', False):
                basic_fields.append(field_name)
        # Fetch values from the server
        if self.ids:
            rows = self.__class__.read(
                self.ids, basic_fields, context=context, load='_classic_write'
            )
            ids_fetched = set()
            for row in rows:
                ids_fetched.add(row['id'])
                for field_name in row:
                    if field_name == 'id':
                        continue
                    self._values[field_name][row['id']] = row[field_name]
            ids_in_error = set(self.ids) - ids_fetched
            if ids_in_error:
                raise ValueError(
                    "There is no '{model}' record with IDs {ids}.".format(
                        model=self._name, ids=list(ids_in_error)
                    )
                )
        # No ID: fields filled with default values
        else:
            default_get = self.__class__.default_get(
                list(self._columns), context=context
            )
            for field_name in self._columns:
                self._values[field_name][None] = default_get.get(
                    field_name, False
                )

    def __getattr__(self, method):
        """Provide a dynamic access to a RPC *instance* method (which applies
        on the current recordset).

        .. doctest::

            >>> Partner = odoo.env['res.partner']
            >>> Partner.write([1], {'name': 'YourCompany'}) # Class method
            True
            >>> partner = Partner.browse(1)
            >>> partner.write({'name': 'YourCompany'})      # Instance method
            True

        """
        if method.startswith('_'):
            return super(Model, self).__getattr__(method)

        def rpc_method(*args, **kwargs):
            """Return the result of the RPC request."""
            args = tuple([self.ids]) + args
            if self._odoo.config['auto_context'] and 'context' not in kwargs:
                kwargs['context'] = self.env.context
            result = self._odoo.execute_kw(self._name, method, args, kwargs)
            return result

        return rpc_method

    def __getitem__(self, key):
        """If `key` is an integer or a slice, return the corresponding record
        selection as a recordset.
        """
        if isinstance(key, int) or isinstance(key, slice):
            return self._browse(self.env, self._ids[key], iterated=self)
        else:
            return getattr(self, key)

    def __int__(self):
        return self.id

    def __eq__(self, other):
        return other.__class__ == self.__class__ and self.id == other.id

    # Need to explicitly declare '__hash__' in Python 3
    # (because '__eq__' is defined)
    __hash__ = BaseModel.__hash__

    def __ne__(self, other):
        return other.__class__ != self.__class__ or self.id != other.id

    def __repr__(self):
        return "Recordset({!r}, {})".format(self._name, self.ids)

    def __iter__(self):
        """Return an iterator over `self`."""
        for id_ in self._ids:
            yield self._browse(self.env, id_, iterated=self)

    def __nonzero__(self):
        return bool(getattr(self, '_ids', True))

    def __len__(self):
        return len(self.ids)

    def __iadd__(self, records):
        if not self._from_record:
            raise error.InternalError("No parent record to update")
        try:
            list(records)
        except TypeError:
            records = [records]
        parent = self._from_record[0]
        field = self._from_record[1]
        updated_values = parent._values_to_write[field.name]
        values = []
        if updated_values.get(parent.id):
            values = updated_values[parent.id][:]  # Copy
        from odoorpc import fields

        for id_ in fields.records2ids(records):
            if (3, id_) in values:
                values.remove((3, id_))
            if (4, id_) not in values:
                values.append((4, id_))
        return IncrementalRecords(values)

    def __isub__(self, records):
        if not self._from_record:
            raise error.InternalError("No parent record to update")
        try:
            list(records)
        except TypeError:
            records = [records]
        parent = self._from_record[0]
        field = self._from_record[1]
        updated_values = parent._values_to_write[field.name]
        values = []
        if updated_values.get(parent.id):
            values = updated_values[parent.id][:]  # Copy
        from odoorpc import fields

        for id_ in fields.records2ids(records):
            if (4, id_) in values:
                values.remove((4, id_))
            if (3, id_) not in values:
                values.append((3, id_))
        return values