| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright 2014 Sébastien Alix |
| 3 |
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl) |
| 4 |
"""Supply the :class:`Environment` class to manage records more efficiently.""" |
| 5 |
|
| 6 |
import sys |
| 7 |
import weakref |
| 8 |
|
| 9 |
from odoorpc import fields |
| 10 |
from odoorpc.models import Model |
| 11 |
from odoorpc.tools import v |
| 12 |
|
| 13 |
FIELDS_RESERVED = ['id', 'ids', '__odoo__', '__osv__', '__data__', 'env'] |
| 14 |
|
| 15 |
|
| 16 |
class Environment(object): |
| 17 |
"""An environment wraps data like the user ID, context or current database |
| 18 |
name, and provides an access to data model proxies. |
| 19 |
|
| 20 |
.. doctest:: |
| 21 |
:options: +SKIP |
| 22 |
|
| 23 |
>>> import odoorpc |
| 24 |
>>> odoo = odoorpc.ODOO('localhost') |
| 25 |
>>> odoo.login('db_name', 'admin', 'password') |
| 26 |
>>> odoo.env |
| 27 |
Environment(db='db_name', uid=1, context={'lang': 'fr_FR', 'tz': 'Europe/Brussels', 'uid': 1}) |
| 28 |
|
| 29 |
.. doctest:: |
| 30 |
:hide: |
| 31 |
|
| 32 |
>>> odoo.env |
| 33 |
Environment(db=..., uid=..., context=...) |
| 34 |
""" |
| 35 |
|
| 36 |
def __init__(self, odoo, db, uid, context): |
| 37 |
self._odoo = odoo |
| 38 |
self._db = db |
| 39 |
self._uid = uid |
| 40 |
self._context = context |
| 41 |
self._registry = {} |
| 42 |
self._dirty = weakref.WeakSet() # set of records updated locally |
| 43 |
|
| 44 |
def __repr__(self): |
| 45 |
return "Environment(db={}, uid={}, context={})".format( |
| 46 |
repr(self._db), self._uid, self._context |
| 47 |
) |
| 48 |
|
| 49 |
@property |
| 50 |
def dirty(self): |
| 51 |
""" |
| 52 |
.. warning:: |
| 53 |
|
| 54 |
This property is used internally and should not be used directly. |
| 55 |
As such, it should not be referenced in the user documentation. |
| 56 |
|
| 57 |
List records having local changes. |
| 58 |
These changes can be committed to the server with the :func:`commit` |
| 59 |
method, or invalidated with :func:`invalidate`. |
| 60 |
""" |
| 61 |
return self._dirty |
| 62 |
|
| 63 |
@property |
| 64 |
def context(self): |
| 65 |
"""The context of the user connected. |
| 66 |
|
| 67 |
.. doctest:: |
| 68 |
:options: +SKIP |
| 69 |
|
| 70 |
>>> odoo.env.context |
| 71 |
{'lang': 'en_US', 'tz': 'Europe/Brussels', 'uid': 2} |
| 72 |
|
| 73 |
.. doctest:: |
| 74 |
:hide: |
| 75 |
|
| 76 |
>>> from pprint import pprint as pp |
| 77 |
>>> pp(odoo.env.context) |
| 78 |
{'lang': 'en_US', 'tz': 'Europe/Brussels', 'uid': ...} |
| 79 |
""" |
| 80 |
return self._context |
| 81 |
|
| 82 |
@property |
| 83 |
def db(self): |
| 84 |
"""The database currently used. |
| 85 |
|
| 86 |
.. doctest:: |
| 87 |
:options: +SKIP |
| 88 |
|
| 89 |
>>> odoo.env.db |
| 90 |
'db_name' |
| 91 |
|
| 92 |
.. doctest:: |
| 93 |
:hide: |
| 94 |
|
| 95 |
>>> odoo.env.db == DB |
| 96 |
True |
| 97 |
""" |
| 98 |
return self._db |
| 99 |
|
| 100 |
def commit(self): |
| 101 |
"""Commit dirty records to the server. This method is automatically |
| 102 |
called when the `auto_commit` option is set to `True` (default). |
| 103 |
It can be useful to set the former option to `False` to get better |
| 104 |
performance by reducing the number of RPC requests generated. |
| 105 |
|
| 106 |
With `auto_commit` set to `True` (default behaviour), each time a value |
| 107 |
is set on a record field a RPC request is sent to the server to update |
| 108 |
the record: |
| 109 |
|
| 110 |
.. doctest:: |
| 111 |
|
| 112 |
>>> user = odoo.env.user |
| 113 |
>>> user.name = "Joe" # write({'name': "Joe"}) |
| 114 |
>>> user.email = "[email protected]" # write({'email': "[email protected]"}) |
| 115 |
|
| 116 |
With `auto_commit` set to `False`, changes on a record are sent all at |
| 117 |
once when calling the :func:`commit` method: |
| 118 |
|
| 119 |
.. doctest:: |
| 120 |
|
| 121 |
>>> odoo.config['auto_commit'] = False |
| 122 |
>>> user = odoo.env.user |
| 123 |
>>> user.name = "Joe" |
| 124 |
>>> user.email = "[email protected]" |
| 125 |
>>> user in odoo.env.dirty |
| 126 |
True |
| 127 |
>>> odoo.env.commit() # write({'name': "Joe", 'email': "[email protected]"}) |
| 128 |
>>> user in odoo.env.dirty |
| 129 |
False |
| 130 |
|
| 131 |
Only one RPC request is generated in the last case. |
| 132 |
""" |
| 133 |
# Iterate on a new set, as we remove record during iteration from the |
| 134 |
# original one |
| 135 |
for record in set(self.dirty): |
| 136 |
values = {} |
| 137 |
for field in record._values_to_write: |
| 138 |
if record.id in record._values_to_write[field]: |
| 139 |
value = record._values_to_write[field].pop(record.id) |
| 140 |
values[field] = value |
| 141 |
# Store the value in the '_values' dictionary. This |
| 142 |
# operation is delegated to each field descriptor as some |
| 143 |
# values can not be stored "as is" (e.g. magic tuples of |
| 144 |
# 2many fields need to be converted) |
| 145 |
record.__class__.__dict__[field].store(record, value) |
| 146 |
record.write(values) |
| 147 |
self.dirty.remove(record) |
| 148 |
|
| 149 |
def invalidate(self): |
| 150 |
"""Invalidate the cache of records.""" |
| 151 |
self.dirty.clear() |
| 152 |
|
| 153 |
@property |
| 154 |
def lang(self): |
| 155 |
"""Return the current language code. |
| 156 |
|
| 157 |
.. doctest:: |
| 158 |
|
| 159 |
>>> odoo.env.lang |
| 160 |
'en_US' |
| 161 |
""" |
| 162 |
return self.context.get('lang', False) |
| 163 |
|
| 164 |
def ref(self, xml_id): |
| 165 |
"""Return the record corresponding to the given `xml_id` (also called |
| 166 |
external ID). |
| 167 |
Raise an :class:`RPCError <odoorpc.error.RPCError>` if no record |
| 168 |
is found. |
| 169 |
|
| 170 |
.. doctest:: |
| 171 |
|
| 172 |
>>> odoo.env.ref('base.lang_en') |
| 173 |
Recordset('res.lang', [1]) |
| 174 |
|
| 175 |
:return: a :class:`odoorpc.models.Model` instance (recordset) |
| 176 |
:raise: :class:`odoorpc.error.RPCError` |
| 177 |
""" |
| 178 |
if v(self._odoo.version)[0] < 15: |
| 179 |
model, id_ = self._odoo.execute( |
| 180 |
"ir.model.data", "xmlid_to_res_model_res_id", xml_id, True |
| 181 |
) |
| 182 |
module, name = xml_id.split(".", 1) |
| 183 |
model, id_ = self._odoo.execute( |
| 184 |
"ir.model.data", "check_object_reference", module, name, True |
| 185 |
) |
| 186 |
return self[model].browse(id_) |
| 187 |
|
| 188 |
@property |
| 189 |
def uid(self): |
| 190 |
"""The user ID currently logged. |
| 191 |
|
| 192 |
.. doctest:: |
| 193 |
:options: +SKIP |
| 194 |
|
| 195 |
>>> odoo.env.uid |
| 196 |
1 |
| 197 |
|
| 198 |
.. doctest:: |
| 199 |
:hide: |
| 200 |
|
| 201 |
>>> odoo.env.uid in [1, 2] |
| 202 |
True |
| 203 |
""" |
| 204 |
return self._uid |
| 205 |
|
| 206 |
@property |
| 207 |
def user(self): |
| 208 |
"""Return the current user (as a record). |
| 209 |
|
| 210 |
.. doctest:: |
| 211 |
:options: +SKIP |
| 212 |
|
| 213 |
>>> user = odoo.env.user |
| 214 |
>>> user |
| 215 |
Recordset('res.users', [2]) |
| 216 |
>>> user.name |
| 217 |
'Mitchell Admin' |
| 218 |
|
| 219 |
.. doctest:: |
| 220 |
:hide: |
| 221 |
|
| 222 |
>>> user = odoo.env.user |
| 223 |
>>> user.id in [1, 2] |
| 224 |
True |
| 225 |
>>> 'Admin' in user.name |
| 226 |
True |
| 227 |
|
| 228 |
:return: a :class:`odoorpc.models.Model` instance |
| 229 |
:raise: :class:`odoorpc.error.RPCError` |
| 230 |
""" |
| 231 |
return self['res.users'].browse(self.uid) |
| 232 |
|
| 233 |
@property |
| 234 |
def registry(self): |
| 235 |
"""The data model registry. It is a mapping between a model name and |
| 236 |
its corresponding proxy used to generate records. |
| 237 |
As soon as a model is needed the proxy is added to the registry. This |
| 238 |
way the model proxy is ready for a further use (avoiding costly `RPC` |
| 239 |
queries when browsing records through relations). |
| 240 |
|
| 241 |
.. doctest:: |
| 242 |
:hide: |
| 243 |
|
| 244 |
>>> odoo.env.registry.clear() |
| 245 |
|
| 246 |
>>> odoo.env.registry |
| 247 |
{} |
| 248 |
>>> odoo.env.user.company_id.name # 'res.users' and 'res.company' Model proxies will be fetched |
| 249 |
'YourCompany' |
| 250 |
>>> from pprint import pprint |
| 251 |
>>> pprint(odoo.env.registry) |
| 252 |
{'res.company': Model('res.company'), 'res.users': Model('res.users')} |
| 253 |
|
| 254 |
If you need to regenerate the model proxy, simply delete it from the |
| 255 |
registry: |
| 256 |
|
| 257 |
>>> del odoo.env.registry['res.company'] |
| 258 |
|
| 259 |
To delete all model proxies: |
| 260 |
|
| 261 |
>>> odoo.env.registry.clear() |
| 262 |
>>> odoo.env.registry |
| 263 |
{} |
| 264 |
""" |
| 265 |
return self._registry |
| 266 |
|
| 267 |
def __getitem__(self, model): |
| 268 |
"""Return the model class corresponding to `model`. |
| 269 |
|
| 270 |
>>> Partner = odoo.env['res.partner'] |
| 271 |
>>> Partner |
| 272 |
Model('res.partner') |
| 273 |
|
| 274 |
:return: a :class:`odoorpc.models.Model` class |
| 275 |
""" |
| 276 |
if model not in self.registry: |
| 277 |
# self.registry[model] = Model(self._odoo, self, model) |
| 278 |
self.registry[model] = self._create_model_class(model) |
| 279 |
return self.registry[model] |
| 280 |
|
| 281 |
def __call__(self, context=None): |
| 282 |
"""Return an environment based on `self` with a different |
| 283 |
user context. |
| 284 |
""" |
| 285 |
context = self.context if context is None else context |
| 286 |
env = Environment(self._odoo, self._db, self._uid, context) |
| 287 |
env._dirty = self._dirty |
| 288 |
env._registry = self._registry |
| 289 |
return env |
| 290 |
|
| 291 |
def __contains__(self, model): |
| 292 |
"""Check if the given `model` exists on the server. |
| 293 |
|
| 294 |
>>> 'res.partner' in odoo.env |
| 295 |
True |
| 296 |
|
| 297 |
:return: `True` or `False` |
| 298 |
""" |
| 299 |
model_exists = self._odoo.execute( |
| 300 |
'ir.model', 'search', [('model', '=', model)] |
| 301 |
) |
| 302 |
return bool(model_exists) |
| 303 |
|
| 304 |
def _create_model_class(self, model): |
| 305 |
"""Generate the model proxy class. |
| 306 |
|
| 307 |
:return: a :class:`odoorpc.models.Model` class |
| 308 |
""" |
| 309 |
cls_name = model.replace('.', '_') |
| 310 |
# Hack for Python 2 (no need to do this for Python 3) |
| 311 |
if sys.version_info[0] < 3: |
| 312 |
# noqa: F821 |
| 313 |
if isinstance(cls_name, unicode): # noqa: F821 |
| 314 |
cls_name = cls_name.encode('utf-8') |
| 315 |
# Retrieve server fields info and generate corresponding local fields |
| 316 |
attrs = { |
| 317 |
'_env': self, |
| 318 |
'_odoo': self._odoo, |
| 319 |
'_name': model, |
| 320 |
'_columns': {}, |
| 321 |
} |
| 322 |
fields_get = self._odoo.execute(model, 'fields_get') |
| 323 |
for field_name, field_data in fields_get.items(): |
| 324 |
if field_name not in FIELDS_RESERVED: |
| 325 |
Field = fields.generate_field(field_name, field_data) |
| 326 |
attrs['_columns'][field_name] = Field |
| 327 |
attrs[field_name] = Field |
| 328 |
return type(cls_name, (Model,), attrs) |