size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
231
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon={ "external_dependencies_override": { "python": {"contextvars": 'contextvars;python_version<"3.7"'} } }, )
23.1
231
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
656
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Base Rest Auth Jwt", "summary": """ Base Rest: Add support for the auth_jwt security policy into the openapi documentation""", "version": "15.0.1.1.0", "license": "LGPL-3", "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/rest-framework", "depends": ["base_rest", "auth_jwt"], "maintainers": ["lmignon"], "installable": False, "auto_install": True, "external_dependencies": { "python": [ "apispec>=4.0.0", ] }, }
29.818182
656
550
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.component.core import AbstractComponent from ..apispec.rest_method_security_plugin import RestMethodSecurityPlugin class BaseRestService(AbstractComponent): _inherit = "base.rest.service" def _get_api_spec(self, **params): spec = super(BaseRestService, self)._get_api_spec(**params) plugin = RestMethodSecurityPlugin(self) plugin.init_spec(spec) spec.plugins.append(plugin) return spec
32.352941
550
714
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.http import request from odoo.addons.component.core import AbstractComponent, Component class AbstractAuthJwtAuthenticatedPartnerProvider(AbstractComponent): _name = "abstract.auth.jwt.authenticated.partner.provider" def _get_authenticated_partner_id(self): return request.jwt_partner_id class BaseRestAuthJwtComponentContextProvider(Component): _name = "base.rest.auth.jwt.component.context.provider" _inherit = [ "abstract.auth.jwt.authenticated.partner.provider", "base.rest.service.context.provider", ] _usage = "auth_jwt_component_context_provider"
31.043478
714
1,333
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from apispec import BasePlugin class RestMethodSecurityPlugin(BasePlugin): def __init__(self, service): super(RestMethodSecurityPlugin, self).__init__() self._service = service def init_spec(self, spec): super(RestMethodSecurityPlugin, self).init_spec(spec) self.spec = spec self.openapi_version = spec.openapi_version jwt_scheme = { "type": "http", "scheme": "bearer", "bearerFormat": "JWT", "name": "jwt", "description": "Enter JWT Bearer Token ** only **", } spec.components.security_scheme("jwt", jwt_scheme) def operation_helper(self, path=None, operations=None, **kwargs): routing = kwargs.get("routing") if not routing: super(RestMethodSecurityPlugin, self).operation_helper( path, operations, **kwargs ) if not operations: return auth = routing.get("auth", self.spec._params.get("default_auth")) if auth and auth.startswith("jwt"): for _method, params in operations.items(): security = params.setdefault("security", []) security.append({"jwt": []})
36.027027
1,333
504
py
PYTHON
15.0
# Copyright 2021 Wakari SRL (http://www.wakari.be) # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { "name": "REST Authentication Service", "summary": "Login/logout from session using a REST call", "version": "15.0.1.0.1", "development_status": "Alpha", "license": "LGPL-3", "website": "https://github.com/OCA/rest-framework", "author": "Wakari, Odoo Community Association (OCA)", "depends": ["base_rest"], "data": [], "installable": True, }
33.6
504
1,858
py
PYTHON
15.0
# Copyright 2021 Wakari SRL # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import odoo.tests.common from odoo.http import root from odoo.tests import new_test_user from odoo.tests.common import HttpCase HOST = "127.0.0.1" PORT = odoo.tools.config["http_port"] @odoo.tests.tagged("post_install", "-at_install") class TestSessionRestAPI(HttpCase): def setUp(self): super().setUp() self.password = "test_password" self.user = new_test_user(self.env, login="test_user", password=self.password) @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_01(self): """Test authentication""" params = { "db": self.env.cr.dbname, "login": self.user.login, "password": self.password, } url = "http://{}:{}{}".format(HOST, PORT, "/session/auth/login") response = self.opener.post(url, json=params) self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["Content-Type"], "application/json") data = response.json() session = root.session_store.get(data["session"]["sid"]) self.assertEqual(session.login, self.user.login) @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_02(self): """Test logout""" self.authenticate(self.user.login, self.password) self.assertEqual(self.session.login, self.user.login) url = "http://{}:{}{}".format(HOST, PORT, "/session/auth/logout") response = self.opener.post( url, headers={"X-Openerp-Session-Id": self.session.sid} ) self.assertEqual(response.status_code, 200) self.assertEqual(response.headers["Content-Type"], "application/json") session = root.session_store.get(self.session.sid) self.assertIsNone(session.login)
38.708333
1,858
179
py
PYTHON
15.0
from odoo.addons.base_rest.controllers import main class SessionRestController(main.RestController): _root_path = "/session/" _collection_name = "session.rest.services"
29.833333
179
1,765
py
PYTHON
15.0
import datetime from odoo import fields from odoo.http import db_monodb, request, root from odoo.service import security from odoo.addons.base_rest import restapi from odoo.addons.component.core import Component def _rotate_session(httprequest): if httprequest.session.rotate: root.session_store.delete(httprequest.session) httprequest.session.sid = root.session_store.generate_key() if httprequest.session.uid: httprequest.session.session_token = security.compute_session_token( httprequest.session, request.env ) httprequest.session.modified = True class SessionAuthenticationService(Component): _inherit = "base.rest.service" _name = "session.authenticate.service" _usage = "auth" _collection = "session.rest.services" @restapi.method([(["/login"], "POST")], auth="public") def authenticate(self): params = request.params db_name = params.get("db", db_monodb()) request.session.authenticate(db_name, params["login"], params["password"]) result = request.env["ir.http"].session_info() # avoid to rotate the session outside of the scope of this method # to ensure that the session ID does not change after this method _rotate_session(request) request.session.rotate = False expiration = datetime.datetime.utcnow() + datetime.timedelta(days=90) result["session"] = { "sid": request.session.sid, "expires_at": fields.Datetime.to_string(expiration), } return result @restapi.method([(["/logout"], "POST")], auth="user") def logout(self): request.session.logout(keep_db=True) return {"message": "Successful logout"}
36.770833
1,765
668
py
PYTHON
15.0
from marshmallow import fields from .core import ModelSerializer class GenericAbstractSerializer(ModelSerializer): _name = "generic.abstract.serializer" _model = "base" _register = False def __init__(self, *args, **kwargs): if kwargs.get("_model"): self._model = kwargs.pop("_model") super().__init__(*args, **kwargs) class GenericMinimalSerializer(GenericAbstractSerializer): _name = "generic.minimal.serializer" _model_fields = ["id", "display_name"] id = fields.Integer(dump_only=True) display_name = fields.String(dump_only=True) def to_recordset(self): return self.get_odoo_record()
26.72
668
3,593
py
PYTHON
15.0
import logging from marshmallow import fields from odoo import fields as odoo_fields from odoo.addons.datamodel.fields import NestedModel _logger = logging.getLogger(__name__) __all__ = ["convert_field"] class Binary(fields.Raw): def _serialize(self, value, attr, obj, **kwargs): res = super()._serialize(value, attr, obj, **kwargs) if isinstance(res, bytes): res = res.decode("utf-8") return res class FieldConverter: def __init__(self, odoo_field): self.odoo_field = odoo_field def _marshmallow_field_class(self): pass def _get_kwargs(self): kwargs = { "required": self.odoo_field.required, "allow_none": not self.odoo_field.required, } if self.odoo_field.readonly: kwargs["dump_only"] = True return kwargs def convert_to_marshmallow(self): marshmallow_field_class = self._marshmallow_field_class() kwargs = self._get_kwargs() return marshmallow_field_class(**kwargs) class BooleanConverter(FieldConverter): def _get_kwargs(self): kwargs = super()._get_kwargs() kwargs["falsy"] = fields.Boolean.falsy.union({None}) return kwargs def _marshmallow_field_class(self): return fields.Boolean class IntegerConverter(FieldConverter): def _marshmallow_field_class(self): return fields.Integer class FloatConverter(FieldConverter): def _marshmallow_field_class(self): return fields.Float class StringConverter(FieldConverter): def _marshmallow_field_class(self): return fields.String class DateConverter(FieldConverter): def _marshmallow_field_class(self): return fields.Date class DatetimeConverter(FieldConverter): def _marshmallow_field_class(self): return fields.DateTime class RawConverter(FieldConverter): def _marshmallow_field_class(self): return fields.Raw class BinaryConverter(FieldConverter): def _marshmallow_field_class(self): return Binary class RelationalConverter(FieldConverter): def _get_kwargs(self): kwargs = super()._get_kwargs() kwargs["many"] = isinstance( self.odoo_field, (odoo_fields.One2many, odoo_fields.Many2many) ) kwargs["nested"] = "generic.minimal.serializer" kwargs["metadata"] = {"odoo_model": self.odoo_field.comodel_name} return kwargs def _marshmallow_field_class(self): return NestedModel FIELDS_CONV = { odoo_fields.Boolean: BooleanConverter, odoo_fields.Integer: IntegerConverter, odoo_fields.Id: IntegerConverter, odoo_fields.Float: FloatConverter, odoo_fields.Monetary: FloatConverter, # should we use a Decimal instead? odoo_fields.Char: StringConverter, odoo_fields.Text: StringConverter, odoo_fields.Html: StringConverter, odoo_fields.Selection: RawConverter, odoo_fields.Date: DateConverter, odoo_fields.Datetime: DatetimeConverter, odoo_fields.Binary: BinaryConverter, odoo_fields.Image: BinaryConverter, odoo_fields.One2many: RelationalConverter, odoo_fields.Many2one: RelationalConverter, odoo_fields.Many2many: RelationalConverter, } def convert_field(odoo_field): field_cls = type(odoo_field) if field_cls in FIELDS_CONV: return FIELDS_CONV[field_cls](odoo_field).convert_to_marshmallow() else: _logger.warning( "Not implemented: Odoo fields of type {} cannot be " "translated into Marshmallow fields".format(field_cls) )
27.427481
3,593
8,953
py
PYTHON
15.0
from odoo import _, models from odoo.exceptions import ValidationError from odoo.addons.datamodel.core import Datamodel, MetaDatamodel from .field_converter import convert_field class class_or_instancemethod(classmethod): # pylint: disable=class-camelcase def __get__(self, instance, type_): descr_get = super().__get__ if instance is None else self.__func__.__get__ return descr_get(instance, type_) class MetaModelSerializer(MetaDatamodel): def __init__(self, name, bases, attrs): super(MetaModelSerializer, self).__init__(name, bases, attrs) class ModelSerializer(Datamodel, metaclass=MetaModelSerializer): _inherit = "base" _register = False _model = None _model_fields = [] def dump(self, many=None): with self.__dump_mode_on__(): dump = self.__schema__.dump(self, many=many) return dump @classmethod def _check_nested_class(cls, marshmallow_field, registry): """If `marshmallow_field` is a nested datamodel (relational field), we check if the nested datamodel class exists """ nested_name = getattr(marshmallow_field, "datamodel_name", None) if nested_name and nested_name not in registry: raise ValidationError( _("'{}' datamodel does not exist").format(nested_name) ) @classmethod def _extend_from_odoo_model(cls, registry, env): """Extend the datamodel to contain the declared Odoo model fields""" attrs = { "_inherit": cls._name, "_model_fields": getattr(cls, "_model_fields", []), "_model": getattr(cls, "_model", None), } bases = (ModelSerializer,) name = cls.__name__ + "Child" parent_class = registry[cls._name] has_model_fields = bool(attrs["_model_fields"]) if getattr(parent_class, "_model_fields", None): has_model_fields = True if getattr(parent_class, "_model", None): if attrs["_model"] and attrs["_model"] != parent_class._model: raise ValidationError( _( "Error in {}: Model Serializers cannot inherit " "from a class having a different '_model' attribute" ).format(cls.__name__) ) attrs["_model"] = parent_class._model if not (attrs["_model"] and has_model_fields): raise ValidationError( _( "Error in {}: Model Serializers require '_model' and " "'_model_fields' attributes to be defined" ).format(cls.__name__) ) odoo_model = env[attrs["_model"]] for field_name in cls._model_fields: if not hasattr(cls, field_name): odoo_field = odoo_model._fields[field_name] marshmallow_field = convert_field(odoo_field) if marshmallow_field: attrs[field_name] = marshmallow_field else: marshmallow_field = cls.__schema_class__._declared_fields[field_name] cls._check_nested_class(marshmallow_field, registry) return MetaDatamodel(name, bases, attrs) @property def _model_name(self): if self.context.get("odoo_model"): return self.context["odoo_model"] return self._model @_model_name.setter def _model_name(self, value): if not self.context: self.context = {} self.context["odoo_model"] = value @classmethod def from_recordset(cls, recordset, *, many=False): """Transform a recordset into a (list of) datamodel(s)""" def convert_null_value(val): if val: return val if val is False or isinstance(val, models.BaseModel): return None return val res = [] datamodels = recordset.env.datamodels recordset = recordset if many else recordset[:1] for record in recordset: instance = cls(partial=True, context={"odoo_model": record._name}) for model_field in cls._model_fields: schema_field = instance.__schema__.fields[model_field] nested_datamodel_name = getattr(schema_field, "datamodel_name", None) if nested_datamodel_name: nested_datamodel_class = datamodels[nested_datamodel_name] if hasattr(nested_datamodel_class, "from_recordset"): setattr( instance, model_field, nested_datamodel_class.from_recordset( record[model_field], many=schema_field.many ), ) else: value = convert_null_value(record[model_field]) setattr(instance, model_field, value) res.append(instance) if not many: return res[0] if res else None return res def get_odoo_record(self): """Get an existing record matching `self`. Meant to be overridden TODO: optimize this to deal with multiple instances at once """ odoo_model = self.env[self._model_name] if "id" in self._model_fields and getattr(self, "id", None): return odoo_model.browse(self.id) return odoo_model.browse([]) def _new_odoo_record(self): odoo_model = self.env[self._model_name] default_values = odoo_model.default_get(odoo_model._fields.keys()) return odoo_model.new(default_values) def _process_model_value(self, value, model_field): if hasattr(self, "validate_{}".format(model_field)): return getattr(self, "validate_{}".format(model_field))(value) return value def _get_partial_fields(self): """Return the list of fields actually used to instantiate `self`""" res = [] received_keys = set(self.__schema__._declared_fields) - set( self.__missing_fields__ ) actual_field_names = { field.data_key: name for name, field in self.__schema__._declared_fields.items() if field.data_key } for received_key in received_keys: res.append(actual_field_names.get(received_key) or received_key) return res def convert_to_values(self, model=None): """Transform `self` into a dictionary to create or write an odoo record""" def convert_related_values(dics): res = [(6, 0, [])] for dic in dics: rec_id = dic.pop("id", None) if rec_id: res[0][2].append(rec_id) if dic: res.append((1, rec_id, dic)) else: res.append((4, rec_id)) else: res.append((0, 0, dic)) return res model_name = model or self._model self._model_name = model_name record = self.get_odoo_record() values = {"id": record.id} if record else {} # in case of partial, not all fields are considered received_fields = self._get_partial_fields() model_fields = set(received_fields) & set(self._model_fields) for model_field in model_fields: schema_field = self.__schema__.fields[model_field] if schema_field.dump_only: continue value = getattr(self, model_field) nested_datamodel_name = getattr(schema_field, "datamodel_name", None) nested_datamodel = ( self.env.datamodels[nested_datamodel_name] if nested_datamodel_name else None ) if nested_datamodel and issubclass(nested_datamodel, ModelSerializer): odoo_field = record._fields[model_field] if odoo_field.type == "many2one": value._model_name = odoo_field.comodel_name value = value.to_recordset().id else: nested_values = [ instance.convert_to_values(model=odoo_field.comodel_name) for instance in value ] value = convert_related_values(nested_values) values[model_field] = self._process_model_value(value, model_field) return values def to_recordset(self): """Transform `self` into a corresponding recordset""" record = self.get_odoo_record() values = self.convert_to_values(model=self._model_name) if record: record.write(values) return record else: return self.env[self._model_name].create(values)
39.615044
8,953
1,005
py
PYTHON
15.0
from odoo import models from odoo.addons.datamodel.core import MetaDatamodel, _datamodel_databases from .core import ModelSerializer class DatamodelBuilder(models.AbstractModel): _inherit = "datamodel.builder" def load_datamodels(self, module, datamodels_registry=None): res = super().load_datamodels(module, datamodels_registry=datamodels_registry) datamodels_registry = ( datamodels_registry or _datamodel_databases[self.env.cr.dbname] ) for datamodel_class in MetaDatamodel._modules_datamodels[module]: self._extend_model_serializer(datamodel_class, datamodels_registry) return res def _extend_model_serializer(self, datamodel_class, registry): """Extend the datamodel_class with the fields declared in `_model_fields`""" if issubclass(datamodel_class, ModelSerializer): new_class = datamodel_class._extend_from_odoo_model(registry, self.env) new_class._build_datamodel(registry)
41.875
1,005
658
py
PYTHON
15.0
# Copyright 2021 Wakari SRL (http://www.wakari.be) # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { "name": "Model Serializer", "summary": "Automatically translate Odoo models into Datamodels " "for (de)serialization", "version": "15.0.1.2.0", "development_status": "Alpha", "license": "LGPL-3", "website": "https://github.com/OCA/rest-framework", "author": "Wakari, Odoo Community Association (OCA)", "maintainers": ["fdegrave"], "depends": ["datamodel"], "external_dependencies": { "python": [ "marshmallow", ] }, "data": [], "installable": True, }
29.909091
658
11,171
py
PYTHON
15.0
# Copyright 2021 Wakari SRL # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from marshmallow import fields from odoo import SUPERUSER_ID, fields as odoo_fields from odoo.exceptions import ValidationError from odoo.addons.datamodel.fields import NestedModel from odoo.addons.datamodel.tests.common import DatamodelRegistryCase from ..core import ModelSerializer from ..field_converter import Binary from ..serializers import GenericMinimalSerializer def _schema_field(model_serializer_cls, field_name): schema_cls = model_serializer_cls.__schema_class__ return schema_cls._declared_fields.get(field_name) class TestModelSerializer(DatamodelRegistryCase): """Test build of ModelSerializer""" def setUp(self): super().setUp() self._full_build_model_serializer(GenericMinimalSerializer) def _full_build_model_serializer(self, model_serializer_cls): model_serializer_cls._build_datamodel(self.datamodel_registry) new_cls = model_serializer_cls._extend_from_odoo_model( self.datamodel_registry, self.env ) new_cls._build_datamodel(self.datamodel_registry) return self.env.datamodels[model_serializer_cls._name] def _datamodel_instance(self, serializer_cls, values): datamodel_cls = self._full_build_model_serializer(serializer_cls) instance = datamodel_cls(partial=True) for key in values: setattr(instance, key, values[key]) return instance def test_01_required_attrs(self): """Ensure that ModelSerializer has mandatory attributes""" msg = ".*require '_model' and '_model_fields' attributes.*" with self.assertRaisesRegex(ValidationError, msg): class ModelSerializerBad1(ModelSerializer): _name = "modelserializer_no_model" self._full_build_model_serializer(ModelSerializerBad1) with self.assertRaisesRegex(ValidationError, msg): class ModelSerializerBad2(ModelSerializer): _name = "modelserializer_no_model_fields" _model = "res.partner" self._full_build_model_serializer(ModelSerializerBad2) def test_02_has_field(self): """Ensure that ModelSerializers have the generated fields""" class ModelSerializer1(ModelSerializer): _name = "modelserializer1" _model = "res.partner" _model_fields = ["id"] class ModelSerializer2(ModelSerializer): _name = "modelserializer2" _inherit = "modelserializer1" for serializer_class in (ModelSerializer1, ModelSerializer2): full_cls = self._full_build_model_serializer(serializer_class) self.assertTrue(hasattr(full_cls, "id")) self.assertIsInstance(_schema_field(full_cls, "id"), fields.Integer) def test_03_simple_field_converter(self): """Ensure that non-relational fields are correctly converted""" fields_conversion = { "id": (odoo_fields.Id, fields.Integer, {"dump_only": True}), "create_date": (odoo_fields.Datetime, fields.DateTime, {"dump_only": True}), "date": ( odoo_fields.Date, fields.Date, {"required": False, "allow_none": True}, ), "name": ( odoo_fields.Char, fields.String, {"required": False, "allow_none": True}, ), "comment": ( odoo_fields.Text, fields.String, {"required": False, "allow_none": True}, ), "active": ( odoo_fields.Boolean, fields.Boolean, {"required": False, "allow_none": True}, ), "partner_latitude": ( odoo_fields.Float, fields.Float, {"required": False, "allow_none": True}, ), "active_lang_count": ( odoo_fields.Integer, fields.Integer, {"dump_only": True}, ), "image_1920": ( odoo_fields.Image, Binary, {"required": False, "allow_none": True}, ), } class PartnerSerializer(ModelSerializer): _name = "partner_serializer" _model = "res.partner" _model_fields = list(fields_conversion) full_cls = self._full_build_model_serializer(PartnerSerializer) for field_name in fields_conversion: odoo_field_cls, marsh_field_cls, attrs = fields_conversion[field_name] this_field = _schema_field(full_cls, field_name) self.assertIsInstance(this_field, marsh_field_cls) for attr, attr_val in attrs.items(): msg = ( "Error when converting field {}, wrong " "attribute value ('{}' should be '{}')".format( field_name, attr, attr_val ), ) self.assertEqual(getattr(this_field, attr), attr_val, msg=msg) def test_04_relational_field_converter(self): """Ensure that relational fields are correctly converted""" class PartnerSerializer(ModelSerializer): _name = "partner_serializer" _model = "res.partner" _model_fields = ["user_id"] full_cls = self._full_build_model_serializer(PartnerSerializer) user_field = _schema_field(full_cls, "user_id") self.assertIsInstance(user_field, NestedModel) self.assertEqual(user_field.datamodel_name, "generic.minimal.serializer") self.assertFalse(user_field.many) def test_05_from_recordset(self): """Test `from_recordset` method with only simple fields""" class PartnerSerializer(ModelSerializer): _name = "partner_serializer" _model = "res.partner" _model_fields = ["id", "name"] datamodel_cls = self._full_build_model_serializer(PartnerSerializer) self.partner = self.env["res.partner"].create({"name": "Test Partner"}) datamodel = datamodel_cls.from_recordset(self.partner) self.assertIsInstance(datamodel, datamodel_cls) self.assertEqual(datamodel.id, self.partner.id) self.assertEqual(datamodel.name, self.partner.name) self.assertEqual( set(PartnerSerializer._model_fields), set(datamodel.__schema__.fields.keys()), ) def test_06_from_recordset_nested(self): """Test `from_recordset` method with nested fields, default nested serializer""" class PartnerSerializer(ModelSerializer): _name = "partner_serializer" _model = "res.partner" _model_fields = ["user_id"] datamodel_cls = self._full_build_model_serializer(PartnerSerializer) self.partner = self.env["res.partner"].create({"name": "Test Partner"}) datamodel1 = datamodel_cls.from_recordset(self.partner) self.assertIsInstance(datamodel1, datamodel_cls) self.assertEqual(datamodel1.user_id, None) self.partner.write({"user_id": SUPERUSER_ID}) datamodel2 = datamodel_cls.from_recordset(self.partner) self.assertIsInstance(datamodel2, datamodel_cls) self.assertEqual(datamodel2.user_id.id, SUPERUSER_ID) self.assertEqual( datamodel2.user_id.display_name, self.partner.user_id.display_name ) self.assertEqual( set(PartnerSerializer._model_fields), set(datamodel2.__schema__.fields.keys()), ) def test_07_from_recordset_nested_custom(self): """Test `from_recordset` method with nested fields, custom nested serializer""" class PartnerSerializer(ModelSerializer): _name = "partner_serializer" _model = "res.partner" _model_fields = ["user_id"] user_id = NestedModel("user_serializer") class UserSerializer(ModelSerializer): _name = "user_serializer" _model = "res.users" _model_fields = ["login"] user_dm_cls = self._full_build_model_serializer(UserSerializer) datamodel_cls = self._full_build_model_serializer(PartnerSerializer) user_field = _schema_field(datamodel_cls, "user_id") self.assertEqual(user_field.datamodel_name, "user_serializer") self.partner = self.env["res.partner"].create( {"name": "Test Partner", "user_id": SUPERUSER_ID} ) datamodel = datamodel_cls.from_recordset(self.partner) self.assertIsInstance(datamodel.user_id, user_dm_cls) self.assertEqual(datamodel.user_id.login, self.partner.user_id.login) self.assertEqual( set(UserSerializer._model_fields), set(datamodel.user_id.__schema__.fields.keys()), ) def test_08_to_recordset_write(self): """Test `to_recordset` method with only simple fields, existing partner""" class PartnerSerializer(ModelSerializer): _name = "partner_serializer" _model = "res.partner" _model_fields = ["id", "name"] self.partner = self.env["res.partner"].create({"name": "Test Partner"}) datamodel = self._datamodel_instance( PartnerSerializer, {"id": self.partner.id, "name": self.partner.name + "New"}, ) new_partner = datamodel.to_recordset() self.assertEqual(new_partner, self.partner) self.assertEqual(new_partner.name, datamodel.name) def test_09_to_recordset_relational_write(self): """Test `to_recordset` method with relational fields, existing partner""" class PartnerSerializer(ModelSerializer): _name = "partner_serializer" _model = "res.partner" _model_fields = ["id", "name", "child_ids"] self.partner = self.env["res.partner"].create({"name": "Test Partner"}) self.child_partner = self.env["res.partner"].create( {"name": "Test Child Partner"} ) datamodel_child = self._datamodel_instance( PartnerSerializer, {"id": self.child_partner.id, "name": self.child_partner.name + "New"}, ) datamodel_child2 = self._datamodel_instance( PartnerSerializer, {"name": "Newly Created Partner"}, ) datamodel = self._datamodel_instance( PartnerSerializer, { "id": self.partner.id, "name": self.partner.name + "New", "child_ids": [datamodel_child, datamodel_child2], }, ) new_partner = datamodel.to_recordset() new_partner_child = new_partner.child_ids.filtered( lambda p: p.id == self.child_partner.id ) self.assertTrue(bool(new_partner_child)) self.assertEqual(new_partner_child.name, datamodel_child.name) self.assertTrue("Newly Created Partner" in new_partner.child_ids.mapped("name"))
40.039427
11,171
4,638
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import inspect import logging from collections import OrderedDict _logger = logging.getLogger(__name__) SUPPORTED_META = ["title", "description", "example", "examples"] def cerberus_to_json(schema): """Convert a Cerberus schema to a JSON schema""" result = OrderedDict() required = [] properties = OrderedDict() result["type"] = "object" result["required"] = required result["properties"] = properties for field, spec in list(schema.items()): props = _get_field_props(spec) properties[field] = props if spec.get("required"): required.append(field) # sort required to get the same order on each run and easy comparison into # the tests required.sort() return result def _get_field_props(spec): # noqa: C901 resp = OrderedDict() # dictionary of tuple (json type, json fromat) by cerberus type for # cerberus types requiring a specific mapping to a json type/format type_map = { "dict": ("object",), "list": ("array",), "objectid": ("string", "objectid"), "datetime": ("string", "date-time"), "float": ("number", "float"), } _type = spec.get("type") if _type is None: return resp if "description" in spec: resp["description"] = spec["description"] if "meta" in spec: for key in SUPPORTED_META: value = spec["meta"].get(key) if value: resp[key] = value if "allowed" in spec: resp["enum"] = spec["allowed"] if "default" in spec: resp["default"] = spec["default"] if "minlength" in spec: if _type == "string": resp["minLength"] = spec["minlength"] elif _type == "list": resp["minItems"] = spec["minlength"] if "maxlength" in spec: if _type == "string": resp["maxLength"] = spec["maxlength"] elif _type == "list": resp["maxItems"] = spec["maxlength"] if "min" in spec: if _type in ["number", "integer", "float"]: resp["minimum"] = spec["min"] if "max" in spec: if _type in ["number", "integer", "float"]: resp["maximum"] = spec["max"] if "readonly" in spec: resp["readOnly"] = spec["readonly"] if "regex" in spec: resp["pattern"] = spec["regex"] if "nullable" in spec: resp["nullable"] = spec["nullable"] if "allowed" in spec: resp["enum"] = spec["allowed"] json_type = type_map.get(_type, (_type,)) resp["type"] = json_type[0] if json_type[0] == "object": if "schema" in spec: resp.update(cerberus_to_json(spec["schema"])) additional_properties = {} if "keysrules" in spec: rule_value_type = spec["keysrules"].get("type", "string") if rule_value_type != "string": _logger.debug( "Openapi only support key/value mapping definition where" " the keys are strings. Received %s", rule_value_type, ) if "valuesrules" in spec: values_rules = spec["valuesrules"] rule_value_type = values_rules.get("type", "string") additional_properties["type"] = rule_value_type if "schema" in values_rules: additional_properties.update(cerberus_to_json(values_rules["schema"])) if additional_properties: resp["additionalProperties"] = additional_properties elif json_type[0] == "array": if "schema" in spec: resp["items"] = _get_field_props(spec["schema"]) else: resp["items"] = {"type": "string"} else: try: resp["format"] = json_type[1] # pylint:disable=except-pass except IndexError: pass return resp def _inspect_methods(cls): """Return all methods of a given class as (name, value) pairs sorted by name. inspect.getmembers was initially used. Unfortunately, instance's properties was accessed into the loop and could raise some exception since we are into the startup process and all the resources are not yet initialized. """ results = [] for attribute in inspect.classify_class_attrs(cls): if attribute.kind != "method": continue name = attribute.name method = getattr(cls, name) results.append((name, method)) results.sort(key=lambda pair: pair[0]) return results
31.986207
4,638
712
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import collections class RestServicesDatabases(dict): """Holds a registry of REST services for each database""" _rest_services_databases = RestServicesDatabases() _rest_services_routes = collections.defaultdict(set) _rest_controllers_per_module = collections.defaultdict(list) class RestServicesRegistry(dict): """Holds a registry of REST services where key is the root of the path on which the methods of your ` RestController`` are registred and value is the name of the collection on which your ``RestServiceComponent`` implementing the business logic of your service is registered."""
32.363636
712
1,011
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Base Rest", "summary": """ Develop your own high level REST APIs for Odoo thanks to this addon. """, "version": "15.0.1.2.2", "development_status": "Beta", "license": "LGPL-3", "author": "ACSONE SA/NV, " "Odoo Community Association (OCA)", "maintainers": ["lmignon"], "website": "https://github.com/OCA/rest-framework", "depends": ["component", "web"], "data": [ "views/openapi_template.xml", "views/base_rest_view.xml", ], "assets": { "web.assets_common": [ "base_rest/static/src/scss/base_rest.scss", "base_rest/static/src/js/swagger_ui.js", ], }, "demo": [], "external_dependencies": { "python": [ "cerberus", "pyquerystring", "parse-accept-language", "apispec>=4.0.0", ] }, "installable": True, }
28.083333
1,011
17,628
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import abc import functools import json from cerberus import Validator from odoo import _, http from odoo.exceptions import UserError, ValidationError from .tools import cerberus_to_json def method(routes, input_param=None, output_param=None, **kw): """Decorator marking the decorated method as being a handler for REST requests. The method must be part of a component inheriting from ``base.rest.service``. :param routes: list of tuple (path, http method). path is a string or array. Each tuple determines which http requests and http method will match the decorated method. The path part can be a single string or an array of strings. See werkzeug's routing documentation for the format of path expression ( http://werkzeug.pocoo.org/docs/routing/ ). :param: input_param: An instance of an object that implemented ``RestMethodParam``. When processing a request, the http handler first call the from_request method and then call the decorated method with the result of this call. :param: output_param: An instance of an object that implemented ``RestMethodParam``. When processing the result of the call to the decorated method, the http handler first call the `to_response` method with this result and then return the result of this call. :param auth: The type of authentication method. A special auth method named 'public_or_default' can be used. In such a case when the HTTP route will be generated, the auth method will be computed from the '_default_auth' property defined on the controller with 'public_or_' as prefix. The purpose of 'public_or_default' auth method is to provide a way to specify that a method should work for anonymous users but can be enhanced when an authenticated user is know. It implies that when the 'default' auth part of 'public_or_default' will be replaced by the default_auth specified on the controller in charge of registering the web services, an auth method with the same name is defined into odoo to provide such a behavior. In the following example, the auth method on my ping service will be `public_or_jwt` since this authentication method is provided by the auth_jwt addon. .. code-block:: python class PingService(Component): _inherit = "base.rest.service" _name = "ping_service" _usage = "ping" _collection = "test.api.services" @restapi.method( [(["/<string:message>""], "GET")], auth="public_or_auth", ) def _ping(self, message): return {"message": message} class MyRestController(main.RestController): _root_path = '/test/' _collection_name = "test.api.services" _default_auth = "jwt' :param cors: The Access-Control-Allow-Origin cors directive value. When set, this automatically adds OPTIONS to allowed http methods so the Odoo request handler will accept it. :param bool csrf: Whether CSRF protection should be enabled for the route. Defaults to ``False`` :param bool save_session: Whether HTTP session should be saved into the session store: Default to ``True`` """ def decorator(f): _routes = [] for paths, http_methods in routes: if not isinstance(paths, list): paths = [paths] if not isinstance(http_methods, list): http_methods = [http_methods] if kw.get("cors") and "OPTIONS" not in http_methods: http_methods.append("OPTIONS") for m in http_methods: _routes.append(([p for p in paths], m)) routing = { "routes": _routes, "input_param": input_param, "output_param": output_param, } routing.update(kw) @functools.wraps(f) def response_wrap(*args, **kw): response = f(*args, **kw) return response response_wrap.routing = routing response_wrap.original_func = f return response_wrap return decorator class RestMethodParam(abc.ABC): @abc.abstractmethod def from_params(self, service, params): """ This method is called to process the parameters received at the controller. This method should validate and sanitize these paramaters. It could also be used to transform these parameters into the format expected by the called method :param service: :param request: `HttpRequest.params` :return: Value into the format expected by the method """ @abc.abstractmethod def to_response(self, service, result) -> http.Response: """ This method is called to prepare the result of the call to the method in a format suitable by the controller (http.Response or JSON dict). It's responsible for validating and sanitizing the result. :param service: :param obj: :return: http.Response or JSON dict """ @abc.abstractmethod def to_openapi_query_parameters(self, service, spec) -> dict: return {} @abc.abstractmethod def to_openapi_requestbody(self, service, spec) -> dict: return {} @abc.abstractmethod def to_openapi_responses(self, service, spec) -> dict: return {} @abc.abstractmethod def to_json_schema(self, service, spec, direction) -> dict: return {} class BinaryData(RestMethodParam): def __init__(self, mediatypes="*/*", required=False): if not isinstance(mediatypes, list): mediatypes = [mediatypes] self._mediatypes = mediatypes self._required = required def to_json_schema(self, service, spec, direction): return { "type": "string", "format": "binary", "required": self._required, } @property def _binary_content_schema(self): return { mediatype: {"schema": self.to_json_schema(None, None, None)} for mediatype in self._mediatypes } def to_openapi_requestbody(self, service, spec): return {"content": self._binary_content_schema} def to_openapi_query_parameters(self, service, spec): raise NotImplementedError( "BinaryData are not (?yet?) supported as query paramters" ) def to_openapi_responses(self, service, spec): return {"200": {"content": self._binary_content_schema}} def to_response(self, service, result): if not isinstance(result, http.Response): # The response has not been build by the called method... result = self._to_http_response(result) return result def from_params(self, service, params): return params def _to_http_response(self, result): mediatype = self._mediatypes[0] if len(self._mediatypes) == 1 else "*/*" headers = [ ("Content-Type", mediatype), ("X-Content-Type-Options", "nosniff"), ("Content-Disposition", http.content_disposition("file")), ("Content-Length", len(result)), ] return http.request.make_response(result, headers) class CerberusValidator(RestMethodParam): def __init__(self, schema): """ :param schema: can be dict as cerberus schema, an instance of cerberus.Validator or a sting with the method name to call on the service to get the schema or the validator """ self._schema = schema def from_params(self, service, params): validator = self.get_cerberus_validator(service, "input") if validator.validate(params): return validator.document raise UserError(_("BadRequest %s") % validator.errors) def to_response(self, service, result): validator = self.get_cerberus_validator(service, "output") if validator.validate(result): return validator.document raise SystemError(_("Invalid Response %s") % validator.errors) def to_openapi_query_parameters(self, service, spec): json_schema = self.to_json_schema(service, spec, "input") parameters = [] for prop, spec in list(json_schema["properties"].items()): params = { "name": prop, "in": "query", "required": prop in json_schema["required"], "allowEmptyValue": spec.get("nullable", False), "default": spec.get("default"), } if spec.get("schema"): params["schema"] = spec.get("schema") else: params["schema"] = {"type": spec["type"]} if spec.get("items"): params["schema"]["items"] = spec.get("items") if "enum" in spec: params["schema"]["enum"] = spec["enum"] parameters.append(params) if spec["type"] == "array": # To correctly handle array into the url query string, # the name must ends with [] params["name"] = params["name"] + "[]" return parameters def to_openapi_requestbody(self, service, spec): json_schema = self.to_json_schema(service, spec, "input") return {"content": {"application/json": {"schema": json_schema}}} def to_openapi_responses(self, service, spec): json_schema = self.to_json_schema(service, spec, "output") return {"200": {"content": {"application/json": {"schema": json_schema}}}} def get_cerberus_validator(self, service, direction): assert direction in ("input", "output") schema = self._schema if isinstance(self._schema, str): validator_component = service.component(usage="cerberus.validator") schema = validator_component.get_validator_handler( service, self._schema, direction )() if isinstance(schema, Validator): return schema if isinstance(schema, dict): return Validator(schema, purge_unknown=True) raise Exception(_("Unable to get cerberus schema from %s") % self._schema) def to_json_schema(self, service, spec, direction): schema = self.get_cerberus_validator(service, direction).schema return cerberus_to_json(schema) class CerberusListValidator(CerberusValidator): def __init__(self, schema, min_items=None, max_items=None, unique_items=None): """ :param schema: Cerberus list item schema can be dict as cerberus schema, an instance of cerberus.Validator or a sting with the method name to call on the service to get the schema or the validator :param min_items: A list instance is valid against "min_items" if its size is greater than, or equal to, min_items. The value MUST be a non-negative integer. :param max_items: A list instance is valid against "max_items" if its size is less than, or equal to, max_items. The value MUST be a non-negative integer. :param unique_items: Used to document that the list should only contain unique items. (Not enforced at validation time) """ super(CerberusListValidator, self).__init__(schema=schema) self._min_items = min_items self._max_items = max_items self._unique_items = unique_items def from_params(self, service, params): return self._do_validate(service, data=params, direction="input") def to_response(self, service, result): return self._do_validate(service, data=result, direction="output") def to_openapi_query_parameters(self, service, spec): raise NotImplementedError("List are not (?yet?) supported as query paramters") # pylint: disable=W8120,W8115 def _do_validate(self, service, data, direction): validator = self.get_cerberus_validator(service, direction) values = [] ExceptionClass = UserError if direction == "input" else SystemError for idx, p in enumerate(data): if not validator.validate(p): raise ExceptionClass( _( "BadRequest item %(idx)s :%(errors)s", idx=idx, errors=validator.errors, ) ) values.append(validator.document) if self._min_items is not None and len(values) < self._min_items: raise ExceptionClass( _( "BadRequest: Not enough items in the list (%(current)s < %(expected)s)", current=len(values), expected=self._min_items, ) ) if self._max_items is not None and len(values) > self._max_items: raise ExceptionClass( _( "BadRequest: Too many items in the list (%(current)s > %(expected)s)", current=len(values), expected=self._max_items, ) ) return values def to_json_schema(self, service, spec, direction): cerberus_schema = self.get_cerberus_validator(service, direction).schema json_schema = cerberus_to_json(cerberus_schema) json_schema = {"type": "array", "items": json_schema} if self._min_items is not None: json_schema["minItems"] = self._min_items if self._max_items is not None: json_schema["maxItems"] = self._max_items if self._unique_items is not None: json_schema["uniqueItems"] = self._unique_items return json_schema class MultipartFormData(RestMethodParam): def __init__(self, parts): """This allows to create multipart/form-data endpoints. :param parts: list of RestMethodParam """ if not isinstance(parts, dict): raise ValidationError(_("You must provide a dict of RestMethodParam")) self._parts = parts def to_openapi_properties(self, service, spec, direction): properties = {} for key, part in self._parts.items(): properties[key] = part.to_json_schema(service, spec, direction) return properties def to_openapi_encoding(self): encodings = {} for key, part in self._parts.items(): if isinstance(part, BinaryData): encodings[key] = {"contentType": ", ".join(part._mediatypes)} return encodings def to_json_schema(self, service, spec, direction): res = { "multipart/form-data": { "schema": { "type": "object", "properties": self.to_openapi_properties(service, spec, direction), } } } encoding = self.to_openapi_encoding() if len(encoding) > 0: res["multipart/form-data"]["schema"]["encoding"] = encoding return res def from_params(self, service, params): for key, part in self._parts.items(): param = None if isinstance(part, BinaryData): param = part.from_params(service, params[key]) else: # If the part is not Binary, it should be JSON try: json_param = json.loads( params[key] ) # multipart ony sends its parts as string except json.JSONDecodeError as error: raise ValidationError( _( "%(key)'s JSON content is malformed: %(error)s", key=key, error=error, ) ) from error param = part.from_params(service, json_param) params[key] = param return params def to_openapi_query_parameters(self, service, spec): raise NotImplementedError( "MultipartFormData are not (?yet?) supported as query paramters" ) def to_openapi_requestbody(self, service, spec): return {"content": self.to_json_schema(service, spec, "input")} def to_openapi_responses(self, service, spec): return {"200": {"content": self.to_json_schema(service, spec, "output")}} def to_response(self, service, result): raise NotImplementedError()
40.711316
17,628
9,087
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # Copyright 2017 Akretion (http://www.akretion.com). # @author Sébastien BEAU <sebastien.beau@akretion.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import datetime import decimal import json import logging import sys import traceback from collections import defaultdict from werkzeug.exceptions import ( BadRequest, Forbidden, HTTPException, InternalServerError, NotFound, Unauthorized, ) from werkzeug.utils import escape import odoo from odoo.exceptions import ( AccessDenied, AccessError, MissingError, UserError, ValidationError, ) from odoo.http import HttpRequest, Root, SessionExpiredException, request from odoo.tools import ustr from odoo.tools.config import config from .core import _rest_services_routes _logger = logging.getLogger(__name__) try: import pyquerystring from accept_language import parse_accept_language except (ImportError, IOError) as err: _logger.debug(err) class JSONEncoder(json.JSONEncoder): def default(self, obj): # pylint: disable=E0202,arguments-differ if isinstance(obj, datetime.datetime): return obj.isoformat() elif isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, decimal.Decimal): return float(obj) return super(JSONEncoder, self).default(obj) BLACKLISTED_LOG_PARAMS = ("password",) def wrapJsonException(exception, include_description=False, extra_info=None): """Wrap exceptions to be rendered as JSON. :param exception: an instance of an exception :param include_description: include full description in payload :param extra_info: dict to provide extra keys to include in payload """ get_original_headers = exception.get_headers exception.traceback = "".join(traceback.format_exception(*sys.exc_info())) def get_body(environ=None): res = {"code": exception.code, "name": escape(exception.name)} description = exception.get_description(environ) if config.get_misc("base_rest", "dev_mode"): # return exception info only if base_rest is in dev_mode res.update({"traceback": exception.traceback, "description": description}) elif include_description: res["description"] = description res.update(extra_info or {}) return JSONEncoder().encode(res) def get_headers(environ=None): """Get a list of headers.""" _headers = [("Content-Type", "application/json")] for key, value in get_original_headers(environ=environ): if key != "Content-Type": _headers.append(key, value) return _headers exception.get_body = get_body exception.get_headers = get_headers if request: httprequest = request.httprequest headers = dict(httprequest.headers) headers.pop("Api-Key", None) message = ( "RESTFULL call to url %s with method %s and params %s " "raise the following error %s" ) params = request.params.copy() for k in params.keys(): if k in BLACKLISTED_LOG_PARAMS: params[k] = "<redacted>" args = (httprequest.url, httprequest.method, params, exception) extra = { "application": "REST Services", "url": httprequest.url, "method": httprequest.method, "params": params, "headers": headers, "status": exception.code, "exception_body": exception.get_body(), } _logger.exception(message, *args, extra=extra) return exception class HttpRestRequest(HttpRequest): """Http request that always return json, usefull for rest api""" def __init__(self, httprequest): super(HttpRestRequest, self).__init__(httprequest) if self.httprequest.mimetype == "application/json": data = self.httprequest.get_data().decode(self.httprequest.charset) try: self.params = json.loads(data) except ValueError as e: msg = "Invalid JSON data: %s" % str(e) _logger.info("%s: %s", self.httprequest.path, msg) raise BadRequest(msg) from e elif self.httprequest.mimetype == "multipart/form-data": # Do not reassign self.params pass else: # We reparse the query_string in order to handle data structure # more information on https://github.com/aventurella/pyquerystring self.params = pyquerystring.parse( self.httprequest.query_string.decode("utf-8") ) self._determine_context_lang() def _determine_context_lang(self): """ In this function, we parse the preferred languages specified into the 'Accept-language' http header. The lang into the context is initialized according to the priority of languages into the headers and those available into Odoo. """ accepted_langs = self.httprequest.headers.get("Accept-language") if not accepted_langs: return parsed_accepted_langs = parse_accept_language(accepted_langs) installed_locale_langs = set() installed_locale_by_lang = defaultdict(list) for lang_code, _name in self.env["res.lang"].get_installed(): installed_locale_langs.add(lang_code) installed_locale_by_lang[lang_code.split("_")[0]].append(lang_code) # parsed_acccepted_langs is sorted by priority (higher first) for lang in parsed_accepted_langs: # we first check if a locale (en_GB) is available into the list of # available locales into Odoo locale = None if lang.locale in installed_locale_langs: locale = lang.locale # if no locale language is installed, we look for an available # locale for the given language (en). We return the first one # found for this language. else: locales = installed_locale_by_lang.get(lang.language) if locales: locale = locales[0] if locale: # reset the context to put our new lang. context = dict(self._context) context["lang"] = locale # the setter defiend in odoo.http.WebRequest reset the env # when setting a new context self.context = context break def _handle_exception(self, exception): """Called within an except block to allow converting exceptions to abitrary responses. Anything returned (except None) will be used as response.""" if isinstance(exception, SessionExpiredException): # we don't want to return the login form as plain html page # we want to raise a proper exception return wrapJsonException(Unauthorized(ustr(exception))) try: return super(HttpRestRequest, self)._handle_exception(exception) except MissingError as e: extra_info = getattr(e, "rest_json_info", None) return wrapJsonException(NotFound(ustr(e)), extra_info=extra_info) except (AccessError, AccessDenied) as e: extra_info = getattr(e, "rest_json_info", None) return wrapJsonException(Forbidden(ustr(e)), extra_info=extra_info) except (UserError, ValidationError) as e: extra_info = getattr(e, "rest_json_info", None) return wrapJsonException( BadRequest(e.args[0]), include_description=True, extra_info=extra_info ) except HTTPException as e: extra_info = getattr(e, "rest_json_info", None) return wrapJsonException(e, extra_info=extra_info) except Exception as e: # flake8: noqa: E722 extra_info = getattr(e, "rest_json_info", None) return wrapJsonException(InternalServerError(e), extra_info=extra_info) def make_json_response(self, data, headers=None, cookies=None): data = JSONEncoder().encode(data) if headers is None: headers = {} headers["Content-Type"] = "application/json" return self.make_response(data, headers=headers, cookies=cookies) ori_get_request = Root.get_request def get_request(self, httprequest): db = httprequest.session.db if db and odoo.service.db.exp_db_exist(db): # on the very first request processed by a worker, # registry is not loaded yet # so we enforce its loading here to make sure that # _rest_services_databases is not empty odoo.registry(db) rest_routes = _rest_services_routes.get(db, []) for root_path in rest_routes: if httprequest.path.startswith(root_path): return HttpRestRequest(httprequest) return ori_get_request(self, httprequest) Root.get_request = get_request
38.337553
9,086
20,963
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from contextlib import contextmanager from odoo.addons.component.core import Component from .. import restapi from .common import TransactionRestServiceRegistryCase class TestControllerBuilder(TransactionRestServiceRegistryCase): """Test Odoo controller builder In this class we test the generation of odoo controllers from the services component """ def setUp(self): super().setUp() self._setup_registry(self) def tearDown(self): self._teardown_registry(self) super().tearDown() def test_01(self): """Test controller generated for old API services In this test we check that the controller generated for services with methods not decorated with the restapi.method decorator contains the required method to route requests to services. In the original implementation, these routes where hardcoded into the base controller. """ # pylint: disable=R7980 class TestServiceOldApi(Component): _inherit = "base.rest.service" _name = "test.ping.service" _usage = "ping" _collection = self._collection_name _description = "test" def get(self, _id, message): pass def search(self, message): return {"response": "Search called search with message " + message} def update(self, _id, message): return {"response": "PUT called with message " + message} # pylint:disable=method-required-super def create(self, **params): return {"response": "POST called with message " + params["message"]} def delete(self, _id): return {"response": "DELETE called with id %s " % _id} def my_method(self, **params): pass def my_instance_method(self, _id, **params): pass # Validator def _validator_search(self): return {"message": {"type": "string"}} # Validator def _validator_get(self): # no parameters by default return {} def _validator_update(self): return {"message": {"type": "string"}} def _validator_create(self): return {"message": {"type": "string"}} def _validator_my_method(self): return {"message": {"type": "string"}} def _validator_my_instance_method(self): return {"message": {"type": "string"}} self.assertFalse(self._get_controller_for(TestServiceOldApi)) self._build_services(self, TestServiceOldApi) controller = self._get_controller_for(TestServiceOldApi) routes = self._get_controller_route_methods(controller) self.assertSetEqual( set(routes.keys()), { "get_get", "get_search", "post_update", "put_update", "post_create", "post_delete", "delete_delete", "post_my_method", "post_my_instance_method", } | self._controller_route_method_names, ) self.assertTrue(controller) # the generated method_name is always the {http_method}_{method_name} method = routes["get_get"] self.assertDictEqual( method.routing, { "methods": ["GET"], "auth": "public", "cors": None, "csrf": False, "routes": [ "/test_controller/ping/<int:id>/get", "/test_controller/ping/<int:id>", ], "save_session": True, }, ) method = routes["get_search"] self.assertDictEqual( method.routing, { "methods": ["GET"], "auth": "public", "cors": None, "csrf": False, "routes": ["/test_controller/ping/search", "/test_controller/ping/"], "save_session": True, }, ) method = routes["post_update"] self.assertDictEqual( method.routing, { "methods": ["POST"], "auth": "public", "cors": None, "csrf": False, "routes": [ "/test_controller/ping/<int:id>/update", "/test_controller/ping/<int:id>", ], "save_session": True, }, ) method = routes["put_update"] self.assertDictEqual( method.routing, { "methods": ["PUT"], "auth": "public", "cors": None, "csrf": False, "routes": ["/test_controller/ping/<int:id>"], "save_session": True, }, ) method = routes["post_create"] self.assertDictEqual( method.routing, { "methods": ["POST"], "auth": "public", "cors": None, "csrf": False, "routes": ["/test_controller/ping/create", "/test_controller/ping/"], "save_session": True, }, ) method = routes["post_delete"] self.assertDictEqual( method.routing, { "methods": ["POST"], "auth": "public", "cors": None, "csrf": False, "routes": ["/test_controller/ping/<int:id>/delete"], "save_session": True, }, ) method = routes["delete_delete"] self.assertDictEqual( method.routing, { "methods": ["DELETE"], "auth": "public", "cors": None, "csrf": False, "routes": ["/test_controller/ping/<int:id>"], "save_session": True, }, ) method = routes["post_my_method"] self.assertDictEqual( method.routing, { "methods": ["POST"], "auth": "public", "cors": None, "csrf": False, "routes": ["/test_controller/ping/my_method"], "save_session": True, }, ) method = routes["post_my_instance_method"] self.assertDictEqual( method.routing, { "methods": ["POST"], "auth": "public", "cors": None, "csrf": False, "routes": ["/test_controller/ping/<int:id>/my_instance_method"], "save_session": True, }, ) def test_02(self): """Test controller generated from services with new API methods In this case we check that the generated controller for a service where the methods are decorated with restapi.method contains the required method to route the requests to the methods """ # pylint: disable=R7980 class TestServiceNewApi(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "test" @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=restapi.CerberusValidator("_get_partner_schema"), auth="public", ) def get(self, _id): return {"name": self.env["res.partner"].browse(_id).name} @restapi.method( [(["/<int:id>/get_name"], "GET")], output_param=restapi.CerberusValidator("_get_partner_schema"), auth="public", ) def get_name(self, _id): return {"name": self.env["res.partner"].browse(_id).name} @restapi.method( [(["/<int:id>/change_name"], "POST")], input_param=restapi.CerberusValidator("_get_partner_schema"), auth="user", ) def update_name(self, _id, **params): pass def _get_partner_schema(self): return {"name": {"type": "string", "required": True}} self.assertFalse(self._get_controller_for(TestServiceNewApi)) self._build_services(self, TestServiceNewApi) controller = self._get_controller_for(TestServiceNewApi) routes = self._get_controller_route_methods(controller) self.assertSetEqual( set(routes.keys()), {"get_get", "get_get_name", "post_update_name"} | self._controller_route_method_names, ) method = routes["get_get"] self.assertDictEqual( method.routing, { "methods": ["GET"], "auth": "public", "cors": None, "csrf": False, "routes": [ "/test_controller/partner/<int:id>/get", "/test_controller/partner/<int:id>", ], "save_session": True, }, ) method = routes["get_get_name"] self.assertDictEqual( method.routing, { "methods": ["GET"], "auth": "public", "cors": None, "csrf": False, "routes": ["/test_controller/partner/<int:id>/get_name"], "save_session": True, }, ) method = routes["post_update_name"] self.assertDictEqual( method.routing, { "methods": ["POST"], "auth": "user", "cors": None, "csrf": False, "routes": ["/test_controller/partner/<int:id>/change_name"], "save_session": True, }, ) def test_03(self): """Check that the controller builder takes care of services inheritance""" # pylint: disable=R7980 class TestPartnerService(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "test" @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=restapi.CerberusValidator("_get_partner_schema"), auth="public", ) def get(self, _id): return {"name": self.env["res.partner"].browse(_id).name} def _get_partner_schema(self): return {"name": {"type": "string", "required": True}} class TestInheritPartnerService(Component): _inherit = "test.partner.service" @restapi.method( [(["/<int:id>/get_name"], "GET")], output_param=restapi.CerberusValidator("_get_partner_schema"), auth="public", ) def get_name(self, _id): return {"name": self.env["res.partner"].browse(_id).name} @restapi.method( [(["/<int:id>/change_name"], "POST")], input_param=restapi.CerberusValidator("_get_partner_schema"), auth="user", ) def update_name(self, _id, **params): pass self.assertFalse(self._get_controller_for(TestPartnerService)) self._build_services(self, TestPartnerService, TestInheritPartnerService) controller = self._get_controller_for(TestPartnerService) routes = self._get_controller_route_methods(controller) self.assertSetEqual( set(routes.keys()), {"get_get", "get_get_name", "post_update_name"} | self._controller_route_method_names, ) method = routes["get_get"] self.assertDictEqual( method.routing, { "methods": ["GET"], "auth": "public", "cors": None, "csrf": False, "routes": [ "/test_controller/partner/<int:id>/get", "/test_controller/partner/<int:id>", ], "save_session": True, }, ) method = routes["get_get_name"] self.assertDictEqual( method.routing, { "methods": ["GET"], "auth": "public", "cors": None, "csrf": False, "routes": ["/test_controller/partner/<int:id>/get_name"], "save_session": True, }, ) method = routes["post_update_name"] self.assertDictEqual( method.routing, { "methods": ["POST"], "auth": "user", "cors": None, "csrf": False, "routes": ["/test_controller/partner/<int:id>/change_name"], "save_session": True, }, ) class TestControllerBuilder2(TransactionRestServiceRegistryCase): """Test Odoo controller builder In this class we test the generation of odoo controllers from the services component The test requires a fresh base controller """ def setUp(self): super().setUp() self._setup_registry(self) def tearDown(self): self._teardown_registry(self) super().tearDown() def test_04(self): """Test controller generated from services with new API methods and old api takes into account the _default_auth Routes directly defined on the RestConroller without auth should also use the _default_auth """ default_auth = "my_default_auth" default_cors = "*" default_csrf = True default_save_session = True self._BaseTestController._default_auth = default_auth self._BaseTestController._default_cors = default_cors self._BaseTestController._default_csrf = default_csrf self._BaseTestController._default_save_session = default_save_session # pylint: disable=R7980 class TestService(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "test" @restapi.method( [(["/new_api_method_with"], "GET")], auth="public", cors="http://my_site", csrf=not default_csrf, save_session=not default_save_session, ) def new_api_method_with(self, _id): return {"name": self.env["res.partner"].browse(_id).name} @restapi.method([(["/new_api_method_without"], "GET")]) def new_api_method_without(self, _id): return {"name": self.env["res.partner"].browse(_id).name} # OLD API method def get(self, _id, message): pass # Validator def _validator_get(self): # no parameters by default return {} self._build_services(self, TestService) controller = self._get_controller_for(TestService) routes = self._get_controller_route_methods(controller) for attr, default in [ ("auth", default_auth), ("cors", default_cors), ("csrf", default_csrf), ("save_session", default_save_session), ]: self.assertEqual( routes["get_new_api_method_without"].routing[attr], default, "wrong %s" % attr, ) self.assertEqual(routes["get_new_api_method_with"].routing["auth"], "public") self.assertEqual( routes["get_new_api_method_with"].routing["cors"], "http://my_site" ) self.assertEqual( routes["get_new_api_method_with"].routing["csrf"], not default_csrf ) self.assertEqual( routes["get_new_api_method_with"].routing["save_session"], not default_save_session, ) self.assertEqual( routes["get_get"].routing["auth"], default_auth, "wrong auth for get_get" ) for attr, default in [ ("auth", default_auth), ("cors", default_cors), ("csrf", default_csrf), ("save_session", default_save_session), ]: self.assertEqual( routes["my_controller_route_without"].routing[attr], default, "wrong %s" % attr, ) routing = routes["my_controller_route_with"].routing for attr, value in [ ("auth", "public"), ("cors", "http://with_cors"), ("csrf", "False"), ("save_session", "False"), ]: self.assertEqual( routing[attr], value, "wrong %s" % attr, ) self.assertEqual( routes["my_controller_route_without_auth_2"].routing["auth"], None, "wrong auth for my_controller_route_without_auth_2", ) def test_05(self): """Test auth="public_or_default" on restapi.method The auth method on the route should be public_or_my_default_auth since the ir.http model provides the _auth_method_public_or_my_default_auth methods """ default_auth = "my_default_auth" self._BaseTestController._default_auth = default_auth # pylint: disable=R7980 class TestService(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "test" @restapi.method( [(["/new_api_method_with_public_or"], "GET")], auth="public_or_default" ) def new_api_method_with_public_or(self, _id): return {"name": self.env["res.partner"].browse(_id).name} # Validator def _validator_get(self): # no parameters by default return {} # delare the auth méthod on ir.http with _add_method( self.env["ir.http"], "_auth_method_public_or_my_default_auth", lambda a: True, ): self._build_services(self, TestService) controller = self._get_controller_for(TestService) routes = self._get_controller_route_methods(controller) self.assertEqual( routes["get_new_api_method_with_public_or"].routing["auth"], "public_or_my_default_auth", ) def test_06(self): """Test auth="public_or_default" on restapi.method The auth method on the route should be the default_auth configurerd on the controller since the ir.http model doesn't provides the _auth_method_public_or_my_default_auth methods """ default_auth = "my_default_auth" self._BaseTestController._default_auth = default_auth # pylint: disable=R7980 class TestService(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "test" @restapi.method( [(["/new_api_method_with_public_or"], "GET")], auth="public_or_default" ) def new_api_method_with_public_or(self, _id): return {"name": self.env["res.partner"].browse(_id).name} # Validator def _validator_get(self): # no parameters by default return {} self._build_services(self, TestService) controller = self._get_controller_for(TestService) routes = self._get_controller_route_methods(controller) self.assertEqual( routes["get_new_api_method_with_public_or"].routing["auth"], "my_default_auth", ) @contextmanager def _add_method(obj, name, method): try: setattr(obj.__class__, name, method) yield finally: delattr(obj.__class__, name)
32.959119
20,962
12,162
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.component.core import Component from .. import restapi from .common import TransactionRestServiceRegistryCase class TestOpenAPIGenerator(TransactionRestServiceRegistryCase): """Test openapi document generation from REST services""" def setUp(self): super().setUp() self._setup_registry(self) def tearDown(self): self._teardown_registry(self) super().tearDown() def test_01(self): """Simple test case""" # pylint: disable=R7980 class PartnerService(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "Sercice description" @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=restapi.CerberusValidator("_get_partner_schema"), auth="public", ) def get(self, _id): """Get the partner information""" def _get_partner_schema(self): return {"name": {"type": "string", "required": True}} self._build_services(self, PartnerService) service = self._get_service_component(self, "partner") openapi = service.to_openapi() self.assertTrue(openapi) # The service url is available at base_url/controller._root_path/_usage url = openapi["servers"][0]["url"] self.assertEqual(self.base_url + "/test_controller/partner", url) # The title is generated from the service usage # The service info must contains a title and a description info = openapi["info"] self.assertEqual(info["title"], "%s REST services" % PartnerService._usage) self.assertEqual(info["description"], PartnerService._description) paths = openapi["paths"] # The paths must contains 2 entries (1 by routes) self.assertSetEqual({"/{id}/get", "/{id}"}, set(openapi["paths"])) for p in ["/{id}/get", "/{id}"]: path = paths[p] # The method for the paths is get self.assertIn("get", path) # The summary is the method docstring get = path["get"] self.assertEqual(get["summary"], "Get the partner information") # The reponse for status 200 is the openapi schema generated from # the cerberus schema returned by the _get_partner_schema method resp = None for item in get["responses"].items(): if item[0] == "200": resp = item[1] self.assertTrue(resp) self.assertDictEqual( resp, { "content": { "application/json": { "schema": { "properties": {"name": {"type": "string"}}, "required": ["name"], "type": "object", } } } }, ) # The path contains parameters self.assertDictEqual( path.get("parameters", [{}])[0], { "in": "path", "name": "id", "required": True, "schema": {"type": "integer", "format": "int32"}, }, ) def test_02(self): """Test path parameters The new api allows you to define paths parameters. In this test we check that these parameters are into the openapi specification """ # pylint: disable=R7980 class PartnerService(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "Sercice description" @restapi.method( [(["/<int:id>/update_name/<string:name>"], "POST")], auth="public" ) def update_name(self, _id, _name): """update_name""" self._build_services(self, PartnerService) service = self._get_service_component(self, "partner") openapi = service.to_openapi() self.assertTrue(openapi) paths = openapi["paths"] self.assertIn("/{id}/update_name/{name}", paths) path = paths["/{id}/update_name/{name}"] self.assertIn("post", path) parameters = path["parameters"] self.assertEqual(2, len(parameters)) name_param = {} id_param = {} for p in parameters: if p["name"] == "id": id_param = p else: name_param = p self.assertDictEqual( name_param, { "in": "path", "name": "name", "required": True, "schema": {"type": "string"}, }, ) self.assertDictEqual( id_param, { "in": "path", "name": "id", "required": True, "schema": {"type": "integer", "format": "int32"}, }, ) # pylint: disable=W8110 def test_03(self): """Test default parameters and default responses You can define default parameters and responses at service level. In this test we check that these parameters and responses are into the openapi specification """ default_params = [ { "name": "API-KEY", "in": "header", "description": "API key for Authorization", "required": True, "schema": {"type": "string"}, "style": "simple", } ] # pylint: disable=R7980 class PartnerService(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "Sercice description" @restapi.method( [(["/<int:id>/update_name/<string:name>"], "POST")], auth="public" ) def update_name(self, _id, _name): """update_name""" def _get_openapi_default_parameters(self): defaults = super()._get_openapi_default_parameters() defaults.extend(default_params) return defaults def _get_openapi_default_responses(self): responses = super()._get_openapi_default_responses().copy() responses["999"] = "TEST" return responses self._build_services(self, PartnerService) service = self._get_service_component(self, "partner") openapi = service.to_openapi() paths = openapi["paths"] self.assertIn("/{id}/update_name/{name}", paths) path = paths["/{id}/update_name/{name}"] self.assertIn("post", path) parameters = path["post"].get("parameters", []) self.assertListEqual(parameters, default_params) responses = path["post"].get("responses", []) self.assertIn("999", responses) def test_04(self): """Binary and Multipart form-data test case""" # pylint: disable=R7980 class AttachmentService(Component): _inherit = "base.rest.service" _name = "test.attachment.service" _usage = "attachment" _collection = self._collection_name _description = "Sercice description" @restapi.method( routes=[(["/<int:id>/download"], "GET")], output_param=restapi.BinaryData(required=True), ) def download(self, _id): """download the attachment""" @restapi.method( routes=[(["/create"], "POST")], input_param=restapi.MultipartFormData( { "file": restapi.BinaryData( mediatypes=["image/png", "image/jpeg"] ), "params": restapi.CerberusValidator("_get_attachment_schema"), } ), output_param=restapi.CerberusValidator("_get_attachment_schema"), ) # pylint: disable=W8106 def create(self, file, params): """create the attachment""" def _get_attachment_schema(self): return {"name": {"type": "string", "required": True}} self._build_services(self, AttachmentService) service = self._get_service_component(self, "attachment") openapi = service.to_openapi() paths = openapi["paths"] # The paths must contains 2 entries (1 by routes) self.assertSetEqual({"/{id}/download", "/create"}, set(openapi["paths"])) path_download = paths["/{id}/download"] resp_download = None for item in path_download["get"]["responses"].items(): if item[0] == "200": resp_download = item[1] self.assertTrue(resp_download) self.assertDictEqual( resp_download, { "content": { "*/*": { "schema": { "type": "string", "format": "binary", "required": True, } } } }, ) # The path contains parameters self.assertDictEqual( path_download.get("parameters", [{}])[0], { "in": "path", "name": "id", "required": True, "schema": {"type": "integer", "format": "int32"}, }, ) path_create = paths["/create"] resp_create = None for item in path_create["post"]["responses"].items(): if item[0] == "200": resp_create = item[1] self.assertTrue(resp_create) self.assertDictEqual( resp_create, { "content": { "application/json": { "schema": { "properties": {"name": {"type": "string"}}, "required": ["name"], "type": "object", } } } }, ) request_create = path_create["post"]["requestBody"] self.assertDictEqual( request_create, { "content": { "multipart/form-data": { "schema": { "type": "object", "properties": { "file": { "type": "string", "format": "binary", "required": False, }, "params": { "type": "object", "properties": { "name": { "type": "string", }, }, "required": ["name"], }, }, "encoding": { "file": {"contentType": "image/png, image/jpeg"} }, } } } }, )
35.982249
12,162
9,480
py
PYTHON
15.0
# Copyright 2017 Akretion (http://www.akretion.com). # Copyright 2020 ACSONE SA/NV # @author Sébastien BEAU <sebastien.beau@akretion.com> # @author Laurent Mignon <laurent.mignon@acsone.eu> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import copy from odoo import http from odoo.tests.common import TransactionCase, get_db_name from odoo.addons.component.core import ( WorkContext, _component_databases, _get_addon_name, ) from odoo.addons.component.tests.common import ( ComponentRegistryCase, TransactionComponentCase, new_rollbacked_env, ) from ..controllers.main import RestController, _PseudoCollection from ..core import ( RestServicesRegistry, _rest_controllers_per_module, _rest_services_databases, ) from ..tools import _inspect_methods class RegistryMixin(object): @classmethod def setUpRegistry(cls): with new_rollbacked_env() as env: service_registration = env["rest.service.registration"] # build the registry of every installed addons services_registry = service_registration._init_global_registry() cls._services_registry = services_registry # ensure that we load only the services of the 'installed' # modules, not 'to install', which means we load only the # dependencies of the tested addons, not the siblings or # children addons service_registration.build_registry( services_registry, states=("installed",) ) # build the services of the current tested addon current_addon = _get_addon_name(cls.__module__) service_registration.load_services(current_addon, services_registry) env["rest.service.registration"]._build_controllers_routes( services_registry ) class RestServiceRegistryCase(ComponentRegistryCase): # pylint: disable=W8106 @staticmethod def _setup_registry(class_or_instance): ComponentRegistryCase._setup_registry(class_or_instance) class_or_instance._service_registry = RestServicesRegistry() # take a copy of registered controllers controllers = http.controllers_per_module http.controllers_per_module = controllers class_or_instance._controllers_per_module = copy.deepcopy( http.controllers_per_module ) class_or_instance._original_addon_rest_controllers_per_module = copy.deepcopy( _rest_controllers_per_module[_get_addon_name(class_or_instance.__module__)] ) db_name = get_db_name() # makes the test component registry available for the db name _component_databases[db_name] = class_or_instance.comp_registry # makes the test service registry available for the db name class_or_instance._original_services_registry = _rest_services_databases.get( db_name, {} ) _rest_services_databases[db_name] = class_or_instance._service_registry # build the services and controller of every installed addons # but the current addon (when running with pytest/nosetest, we # simulate the --test-enable behavior by excluding the current addon # which is in 'to install' / 'to upgrade' with --test-enable). current_addon = _get_addon_name(class_or_instance.__module__) with new_rollbacked_env() as env: RestServiceRegistration = env["rest.service.registration"] RestServiceRegistration.build_registry( class_or_instance._service_registry, states=("installed",), exclude_addons=[current_addon], ) RestServiceRegistration._build_controllers_routes( class_or_instance._service_registry ) # register our components class_or_instance.comp_registry.load_components("base_rest") # Define a base test controller here to avoid to have this controller # registered outside tests class_or_instance._collection_name = "base.rest.test" BaseTestController = class_or_instance._get_test_controller(class_or_instance) class_or_instance._BaseTestController = BaseTestController class_or_instance._controller_route_method_names = { "my_controller_route_without", "my_controller_route_with", "my_controller_route_without_auth_2", } @staticmethod def _get_test_controller(class_or_instance, root_path="/test_controller/"): class BaseTestController(RestController): _root_path = root_path _collection_name = class_or_instance._collection_name _default_auth = "public" @http.route("/my_controller_route_without") def my_controller_route_without(self): return {} @http.route( "/my_controller_route_with", auth="public", cors="http://with_cors", csrf="False", save_session="False", ) def my_controller_route_with(self): return {} @http.route("/my_controller_route_without_auth_2", auth=None) def my_controller_route_without_auth_2(self): return {} return BaseTestController @staticmethod def _teardown_registry(class_or_instance): ComponentRegistryCase._teardown_registry(class_or_instance) http.controllers_per_module = class_or_instance._controllers_per_module db_name = get_db_name() _component_databases[db_name] = class_or_instance._original_components _rest_services_databases[ db_name ] = class_or_instance._original_services_registry class_or_instance._service_registry = {} _rest_controllers_per_module[ _get_addon_name(class_or_instance.__module__) ] = class_or_instance._original_addon_rest_controllers_per_module @staticmethod def _build_services(class_or_instance, *classes): class_or_instance._build_components(*classes) with new_rollbacked_env() as env: RestServiceRegistration = env["rest.service.registration"] current_addon = _get_addon_name(class_or_instance.__module__) RestServiceRegistration.load_services( current_addon, class_or_instance._service_registry ) RestServiceRegistration._build_controllers_routes( class_or_instance._service_registry ) @staticmethod def _get_controller_for(service): addon_name = "{}_{}_{}".format( get_db_name(), service._collection.replace(".", "_"), service._usage.replace(".", "_"), ) controllers = http.controllers_per_module.get(addon_name, []) if not controllers: return return controllers[0][1] @staticmethod def _get_controller_route_methods(controller): methods = {} for name, method in _inspect_methods(controller): if hasattr(method, "routing"): methods[name] = method return methods @staticmethod def _get_service_component(class_or_instance, usage, collection=None): collection = collection or _PseudoCollection( class_or_instance._collection_name, class_or_instance.env ) work = WorkContext( model_name="rest.service.registration", collection=collection, components_registry=class_or_instance.comp_registry, ) return work.component(usage=usage) class TransactionRestServiceRegistryCase(TransactionCase, RestServiceRegistryCase): """Adds Odoo Transaction to inherited from ComponentRegistryCase. This class doesn't set up the registry for you. You're supposed to explicitly call `_setup_registry` and `_teardown_registry` when you need it, either on setUpClass and tearDownClass or setUp and tearDown. class MyTestCase(TransactionRestServiceRegistryCase): def setUp(self): super().setUp() self._setup_registry(self) def tearDown(self): self._teardown_registry(self) super().tearDown() class MyTestCase(TransactionRestServiceRegistryCase): @classmethod def setUpClass(cls): super().setUpClass() cls._setup_registry(cls) @classmethod def tearDownClass(cls): cls._teardown_registry(cls) super().tearDownClass() """ # pylint: disable=W8106 @classmethod def setUpClass(cls): # resolve an inheritance issue (common.TransactionCase does not use # super) TransactionCase.setUpClass() cls.base_url = cls.env["ir.config_parameter"].get_param("web.base.url") @classmethod def tearDownClass(cls): TransactionCase.tearDownClass() class BaseRestCase(TransactionComponentCase, RegistryMixin): @classmethod def setUpClass(cls): super().setUpClass() cls.setUpRegistry() cls.base_url = cls.env["ir.config_parameter"].get_param("web.base.url") cls.registry.enter_test_mode(cls.env.cr) # pylint: disable=W8110 @classmethod def tearDownClass(cls): cls.registry.leave_test_mode() super().tearDownClass()
36.883268
9,479
10,008
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import unittest from cerberus import Validator from odoo.exceptions import UserError from odoo.tests.common import BaseCase, MetaCase from ..components.cerberus_validator import BaseRestCerberusValidator from ..restapi import CerberusListValidator class TestCerberusListValidator(BaseCase, MetaCase("DummyCase", (object,), {})): """Test all the methods that must be implemented by CerberusListValidator to be a valid RestMethodParam""" @classmethod def setUpClass(cls): super().setUpClass() cls.simple_schema = { "name": {"type": "string", "required": True, "nullable": True}, "title": { "type": "string", "nullable": False, "required": False, "allowed": ["mr", "mm"], }, } cls.nested_schema = { "name": {"type": "string", "required": True, "empty": False}, "country": { "type": "dict", "schema": { "id": {"type": "integer", "required": True, "nullable": False}, "name": {"type": "string"}, }, }, } cls.simple_schema_list_validator = CerberusListValidator( schema=cls.simple_schema, min_items=1, max_items=2, unique_items=True ) cls.nested_schema_list_validator = CerberusListValidator( schema=cls.nested_schema ) cls.maxDiff = None def test_to_openapi_responses(self): res = self.simple_schema_list_validator.to_openapi_responses(None, None) self.assertDictEqual( res, { "200": { "content": { "application/json": { "schema": { "items": { "type": "object", "required": ["name"], "properties": { "name": {"nullable": True, "type": "string"}, "title": { "enum": ["mr", "mm"], "nullable": False, "type": "string", }, }, }, "maxItems": 2, "minItems": 1, "type": "array", "uniqueItems": True, } } } } }, ) res = self.nested_schema_list_validator.to_openapi_responses(None, None) self.assertDictEqual( res, { "200": { "content": { "application/json": { "schema": { "items": { "type": "object", "required": ["name"], "properties": { "name": {"type": "string"}, "country": { "type": "object", "required": ["id"], "properties": { "id": { "nullable": False, "type": "integer", }, "name": {"type": "string"}, }, }, }, }, "type": "array", } } } } }, ) def test_to_openapi_requestbody(self): res = self.simple_schema_list_validator.to_openapi_requestbody(None, None) self.assertEqual( res, { "content": { "application/json": { "schema": { "items": { "type": "object", "required": ["name"], "properties": { "name": {"nullable": True, "type": "string"}, "title": { "enum": ["mr", "mm"], "nullable": False, "type": "string", }, }, }, "maxItems": 2, "minItems": 1, "type": "array", "uniqueItems": True, } } } }, ) res = self.nested_schema_list_validator.to_openapi_requestbody(None, None) self.assertDictEqual( res, { "content": { "application/json": { "schema": { "items": { "type": "object", "required": ["name"], "properties": { "name": {"type": "string"}, "country": { "type": "object", "required": ["id"], "properties": { "id": { "nullable": False, "type": "integer", }, "name": {"type": "string"}, }, }, }, }, "type": "array", } } } }, ) def test_to_openapi_query_parameters(self): with self.assertRaises(NotImplementedError): self.simple_schema_list_validator.to_openapi_query_parameters(None, None) def test_from_params_ignore_unknown(self): params = [{"name": "test", "unknown": True}] res = self.simple_schema_list_validator.from_params(None, params=params) self.assertListEqual(res, [{"name": "test"}]) def test_from_params_validation(self): # minItems / maxItems with self.assertRaises(UserError): # minItems = 1 self.simple_schema_list_validator.from_params(None, params=[]) with self.assertRaises(UserError): # maxItems = 2 self.simple_schema_list_validator.from_params( None, params=[{"name": "test"}, {"name": "test"}, {"name": "test"}] ) with self.assertRaises(UserError): # name required self.simple_schema_list_validator.from_params(None, params=[{}]) def test_to_response_ignore_unknown(self): result = [{"name": "test", "unknown": True}] res = self.simple_schema_list_validator.to_response(None, result=result) self.assertListEqual(res, [{"name": "test"}]) def test_to_response_validation(self): # If a response is not conform to the expected schema it's considered # as a programmatic error not a user error with self.assertRaises(SystemError): # minItems = 1 self.simple_schema_list_validator.to_response(None, result=[]) with self.assertRaises(SystemError): # maxItems = 2 self.simple_schema_list_validator.to_response( None, result=[{"name": "test"}, {"name": "test"}, {"name": "test"}] ) with self.assertRaises(SystemError): # name required self.simple_schema_list_validator.to_response(None, result=[{}]) def test_schema_lookup_from_string(self): class MyService(object): def _get_simple_schema(self): return {"name": {"type": "string", "required": True, "nullable": True}} def component(self, *args, **kwargs): return BaseRestCerberusValidator(unittest.mock.Mock()) v = CerberusListValidator(schema="_get_simple_schema") validator = v.get_cerberus_validator(MyService(), "output") self.assertTrue(validator) self.assertDictEqual( validator.root_schema.schema, {"name": {"type": "string", "required": True, "nullable": True}}, ) def test_schema_lookup_from_string_custom_validator(self): class MyService(object): def _get_simple_schema(self): return Validator( {"name": {"type": "string", "required": False}}, require_all=True ) def component(self, *args, **kwargs): return BaseRestCerberusValidator(unittest.mock.Mock()) v = CerberusListValidator(schema="_get_simple_schema") validator = v.get_cerberus_validator(MyService(), "input") self.assertTrue(validator.require_all)
40.518219
10,008
17,128
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import unittest from cerberus import Validator from odoo.exceptions import UserError from odoo.tests.common import BaseCase, MetaCase from ..components.cerberus_validator import BaseRestCerberusValidator from ..restapi import CerberusValidator from ..tools import cerberus_to_json class TestCerberusValidator(BaseCase, MetaCase("DummyCase", (object,), {})): """Test all the methods that must be implemented by CerberusValidator to be a valid RestMethodParam""" @classmethod def setUpClass(cls): super().setUpClass() cls.simple_schema = { "name": {"type": "string", "required": True, "nullable": True}, "title": { "type": "string", "nullable": False, "required": False, "allowed": ["mr", "mm"], }, "age": {"type": "integer", "default": 18}, "interests": {"type": "list", "schema": {"type": "string"}}, } cls.nested_schema = { "name": {"type": "string", "required": True, "empty": False}, "country": { "type": "dict", "schema": { "id": {"type": "integer", "required": True, "nullable": False}, "name": {"type": "string"}, }, }, "is_company": {"type": "boolean"}, } cls.simple_schema_cerberus_validator = CerberusValidator( schema=cls.simple_schema ) cls.nested_schema_cerberus_validator = CerberusValidator( schema=cls.nested_schema ) def test_to_openapi_responses(self): res = self.simple_schema_cerberus_validator.to_openapi_responses(None, None) self.assertDictEqual( res, { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["name"], "properties": { "name": {"nullable": True, "type": "string"}, "title": { "enum": ["mr", "mm"], "nullable": False, "type": "string", }, "age": {"default": 18, "type": "integer"}, "interests": { "type": "array", "items": {"type": "string"}, }, }, } } } } }, ) res = self.nested_schema_cerberus_validator.to_openapi_responses(None, None) self.assertDictEqual( res, { "200": { "content": { "application/json": { "schema": { "type": "object", "required": ["name"], "properties": { "name": {"type": "string"}, "country": { "type": "object", "required": ["id"], "properties": { "id": { "nullable": False, "type": "integer", }, "name": {"type": "string"}, }, }, "is_company": {"type": "boolean"}, }, } } } } }, ) def test_to_openapi_requestbody(self): res = self.simple_schema_cerberus_validator.to_openapi_requestbody(None, None) self.assertEqual( res, { "content": { "application/json": { "schema": { "type": "object", "required": ["name"], "properties": { "name": {"nullable": True, "type": "string"}, "title": { "enum": ["mr", "mm"], "nullable": False, "type": "string", }, "age": {"default": 18, "type": "integer"}, "interests": { "type": "array", "items": {"type": "string"}, }, }, } } } }, ) res = self.nested_schema_cerberus_validator.to_openapi_requestbody(None, None) self.assertDictEqual( res, { "content": { "application/json": { "schema": { "type": "object", "required": ["name"], "properties": { "name": {"type": "string"}, "country": { "type": "object", "required": ["id"], "properties": { "id": {"nullable": False, "type": "integer"}, "name": {"type": "string"}, }, }, "is_company": {"type": "boolean"}, }, } } } }, ) def test_to_openapi_query_parameters(self): res = self.simple_schema_cerberus_validator.to_openapi_query_parameters( None, None ) self.assertListEqual( res, [ { "name": "name", "in": "query", "required": True, "allowEmptyValue": True, "default": None, "schema": {"type": "string"}, }, { "name": "title", "in": "query", "required": False, "allowEmptyValue": False, "default": None, "schema": {"type": "string", "enum": ["mr", "mm"]}, }, { "name": "age", "in": "query", "required": False, "allowEmptyValue": False, "default": 18, "schema": {"type": "integer"}, }, { "name": "interests[]", "in": "query", "required": False, "allowEmptyValue": False, "default": None, "schema": {"type": "array", "items": {"type": "string"}}, }, ], ) res = self.nested_schema_cerberus_validator.to_openapi_query_parameters( None, None ) self.assertListEqual( res, [ { "name": "name", "in": "query", "required": True, "allowEmptyValue": False, "default": None, "schema": {"type": "string"}, }, { "name": "country", "in": "query", "required": False, "allowEmptyValue": False, "default": None, "schema": {"type": "object"}, }, { "name": "is_company", "in": "query", "required": False, "allowEmptyValue": False, "default": None, "schema": {"type": "boolean"}, }, ], ) def test_from_params_add_default(self): params = {"name": "test"} res = self.simple_schema_cerberus_validator.from_params(None, params=params) self.assertDictEqual(res, {"name": "test", "age": 18}) def test_from_params_ignore_unknown(self): params = {"name": "test", "unknown": True} res = self.simple_schema_cerberus_validator.from_params(None, params=params) self.assertDictEqual(res, {"name": "test", "age": 18}) def test_from_params_validation(self): # name is required with self.assertRaises(UserError): self.simple_schema_cerberus_validator.from_params(None, params={}) def test_to_response_add_default(self): result = {"name": "test"} res = self.simple_schema_cerberus_validator.to_response(None, result=result) self.assertDictEqual(res, {"name": "test", "age": 18}) def test_to_response_ignore_unknown(self): result = {"name": "test", "unknown": True} res = self.simple_schema_cerberus_validator.to_response(None, result=result) self.assertDictEqual(res, {"name": "test", "age": 18}) def test_to_response_validation(self): # name is required # If a response is not conform to the expected schema it's considered # as a programmatic error not a user error with self.assertRaises(SystemError): self.simple_schema_cerberus_validator.to_response(None, result={}) def test_schema_lookup_from_string(self): class MyService(object): def _get_simple_schema(self): return {"name": {"type": "string", "required": True, "nullable": True}} def component(self, *args, **kwargs): return BaseRestCerberusValidator(unittest.mock.Mock()) v = CerberusValidator(schema="_get_simple_schema") validator = v.get_cerberus_validator(MyService(), "output") self.assertTrue(validator) self.assertDictEqual( validator.root_schema.schema, {"name": {"type": "string", "required": True, "nullable": True}}, ) def test_schema_lookup_from_string_custom_validator(self): class MyService(object): def _get_simple_schema(self): return Validator( {"name": {"type": "string", "required": False}}, require_all=True ) def component(self, *args, **kwargs): return BaseRestCerberusValidator(unittest.mock.Mock()) v = CerberusValidator(schema="_get_simple_schema") validator = v.get_cerberus_validator(MyService(), "input") self.assertTrue(validator.require_all) def test_custom_validator_handler(self): assertEq = self.assertEqual class CustomBaseRestCerberusValidator(BaseRestCerberusValidator): def get_validator_handler(self, service, method_name, direction): # In your implementation, this is where you can handle how the # validator is retrieved / computed (dispatch to dedicated # components...). assertEq(service, my_service) assertEq(method_name, "my_endpoint") assertEq(direction, "input") # A callable with no parameter is expected. return lambda: Validator( {"name": {"type": "string", "required": False}}, require_all=True ) def has_validator_handler(self, service, method_name, direction): return True class MyService(object): def component(self, *args, **kwargs): return CustomBaseRestCerberusValidator(unittest.mock.Mock()) my_service = MyService() v = CerberusValidator(schema="my_endpoint") validator = v.get_cerberus_validator(my_service, "input") self.assertTrue(validator.require_all) def test_cerberus_key_value_mapping_to_openapi(self): schema = { "indexes": { "type": "dict", "required": True, "nullable": True, "keysrules": {"type": "string"}, "valuesrules": {"type": "string"}, } } openapi = cerberus_to_json(schema) self.assertDictEqual( openapi, { "type": "object", "required": ["indexes"], "properties": { "indexes": { "nullable": True, "type": "object", "additionalProperties": {"type": "string"}, } }, }, ) schema = { "indexes": { "type": "dict", "required": True, "nullable": True, "keysrules": {"type": "string"}, "valuesrules": { "type": "dict", "schema": { "id": { "type": "integer", "required": True, "nullable": False, }, "name": {"type": "string"}, }, }, } } openapi = cerberus_to_json(schema) self.assertDictEqual( openapi, { "type": "object", "required": ["indexes"], "properties": { "indexes": { "nullable": True, "type": "object", "additionalProperties": { "type": "object", "required": ["id"], "properties": { "id": { "nullable": False, "type": "integer", }, "name": {"type": "string"}, }, }, } }, }, ) def test_cerberus_meta_to_openapi(self): schema = { "indexes": { "type": "dict", "meta": { "description": "A key/value mapping where Key is the model " "name used to fill the index and value is the " "index name", "example": { "shopinvader.category": "demo_elasticsearch_backend_" "shopinvader_category_en_US", "shopinvader.variant": "demo_elasticsearch_backend_" "shopinvader_variant_en_US", }, }, "required": True, "nullable": True, "keysrules": {"type": "string"}, "valuesrules": {"type": "string"}, } } openapi = cerberus_to_json(schema) self.assertDictEqual( openapi, { "type": "object", "required": ["indexes"], "properties": { "indexes": { "description": "A key/value mapping where Key is the model " "name used to fill the index and value is " "the index name", "example": { "shopinvader.category": "demo_elasticsearch_backend_" "shopinvader_category_en_US", "shopinvader.variant": "demo_elasticsearch_backend_" "shopinvader_variant_en_US", }, "nullable": True, "type": "object", "additionalProperties": {"type": "string"}, } }, }, )
38.146993
17,128
5,338
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.component.core import Component from odoo.addons.website.tools import MockRequest from .. import restapi from .common import BaseRestCase, TransactionRestServiceRegistryCase class TestServiceContextProvider(TransactionRestServiceRegistryCase): """Test Odoo service context provider In this class we test the context provided by the service context provider """ def setUp(self): super().setUp() self._setup_registry(self) def tearDown(self): self._teardown_registry(self) super().tearDown() def test_01(self): """Test authenticated_partner_id In this case we check that the default service context provider provides no authenticated_partner_id """ # pylint: disable=R7980 class TestServiceNewApi(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "test" @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=restapi.CerberusValidator("_get_partner_schema"), auth="public", ) def get(self, _id): return {"name": self.env["res.partner"].browse(_id).name} self._build_services(self, TestServiceNewApi) controller = self._get_controller_for(TestServiceNewApi) with MockRequest(self.env), controller().service_component( "partner" ) as service: self.assertFalse(service.work.authenticated_partner_id) def test_02(self): """Test authenticated_partner_id In this case we check that the 'abstract.user.authenticated.partner.provider' service context provider provides the current user's partner as authenticated_partner_id """ # pylint: disable=R7880 class TestComponentContextprovider(Component): _name = "test.component.context.provider" _inherit = [ "abstract.user.authenticated.partner.provider", "base.rest.service.context.provider", ] _usage = "test_component_context_provider" self._BaseTestController._component_context_provider = ( "test_component_context_provider" ) # pylint: disable=R7980 class TestServiceNewApi(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "test" @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=restapi.CerberusValidator("_get_partner_schema"), auth="public", ) def get(self, _id): return {"name": self.env["res.partner"].browse(_id).name} self._build_components(TestComponentContextprovider) self._build_services(self, TestServiceNewApi) controller = self._get_controller_for(TestServiceNewApi) with MockRequest(self.env), controller().service_component( "partner" ) as service: self.assertEqual( service.work.authenticated_partner_id, self.env.user.partner_id.id ) def test_03(self): """Test authenticated_partner_id In this case we check that redefining the method _get_authenticated_partner_id changes the authenticated_partner_id provided by the service context provider """ # pylint: disable=R7880 class TestComponentContextprovider(Component): _name = "test.component.context.provider" _inherit = "base.rest.service.context.provider" _usage = "test_component_context_provider" def _get_authenticated_partner_id(self): return 9999 self._BaseTestController._component_context_provider = ( "test_component_context_provider" ) # pylint: disable=R7980 class TestServiceNewApi(Component): _inherit = "base.rest.service" _name = "test.partner.service" _usage = "partner" _collection = self._collection_name _description = "test" @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=restapi.CerberusValidator("_get_partner_schema"), auth="public", ) def get(self, _id): return {"name": self.env["res.partner"].browse(_id).name} self._build_components(TestComponentContextprovider) self._build_services(self, TestServiceNewApi) controller = self._get_controller_for(TestServiceNewApi) with MockRequest(self.env), controller().service_component( "partner" ) as service: self.assertEqual(service.work.authenticated_partner_id, 9999) class CommonCase(BaseRestCase): # dummy test method to pass codecov def test_04(self): self.assertEqual(self.registry.test_cr, self.cr)
35.586667
5,338
850
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class IrRule(models.Model): """Add authenticated_partner_id in record rule evaluation context. This come from the env context, which is populated by the base_rest service layer context provider. """ _inherit = "ir.rule" @api.model def _eval_context(self): ctx = super()._eval_context() if "authenticated_partner_id" in self.env.context: ctx["authenticated_partner_id"] = self.env.context[ "authenticated_partner_id" ] return ctx def _compute_domain_keys(self): """Return the list of context keys to use for caching ``_compute_domain``.""" return super()._compute_domain_keys() + ["authenticated_partner_id"]
31.481481
850
18,240
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). """ REST Service Registy Builder ============================ Register available REST services at the build of a registry. This code is inspired by ``odoo.addons.component.builder.ComponentBuilder`` """ import inspect import logging from werkzeug.routing import Map, Rule import odoo from odoo import http, models from odoo.addons.component.core import WorkContext from .. import restapi from ..components.service import BaseRestService from ..controllers.main import _PseudoCollection from ..core import ( RestServicesRegistry, _rest_controllers_per_module, _rest_services_databases, _rest_services_routes, ) from ..tools import _inspect_methods # Decorator attribute added on a route function (cfr Odoo's route) ROUTING_DECORATOR_ATTR = "routing" _logger = logging.getLogger(__name__) class RestServiceRegistration(models.AbstractModel): """Register REST services into the REST services registry This class allows us to hook the registration of the root urls of all the REST controllers installed into the current database at the end of the Odoo's registry loading, using ``_register_hook``. This method is called after all modules are loaded, so we are sure that we only register REST services installed into the current database. """ _name = "rest.service.registration" _description = "REST Services Registration Model" def _register_hook(self): # This method is called by Odoo when the registry is built, # so in case the registry is rebuilt (cache invalidation, ...), # we have to to rebuild the registry. We use a new # registry so we have an empty cache and we'll add services in it. services_registry = self._init_global_registry() self.build_registry(services_registry) # we also have to remove the RestController from the # controller_per_module registry since it's an abstract controller controllers = http.controllers_per_module["base_rest"] controllers = [ (name, cls) for name, cls in controllers if "RestController" not in name ] http.controllers_per_module["base_rest"] = controllers # create the final controller providing the http routes for # the services available into the current database self._build_controllers_routes(services_registry) def _build_controllers_routes(self, services_registry): for controller_def in services_registry.values(): for service in self._get_services(controller_def["collection_name"]): self._prepare_non_decorated_endpoints(service) self._build_controller(service, controller_def) def _prepare_non_decorated_endpoints(self, service): # Autogenerate routing info where missing RestApiMethodTransformer(service).fix() def _build_controller(self, service, controller_def): _logger.debug("Build service %s for controller_def %s", service, controller_def) base_controller_cls = controller_def["controller_class"] # build our new controller class ctrl_cls = RestApiServiceControllerGenerator( service, base_controller_cls ).generate() # generate an addon name used to register our new controller for # the current database addon_name = "{}_{}_{}".format( self.env.cr.dbname, service._collection.replace(".", "_"), service._usage.replace(".", "_"), ) # put our new controller into the new addon module ctrl_cls.__module__ = "odoo.addons.{}".format(addon_name) # instruct the registry that our fake addon is part of the loaded # modules self.env.registry._init_modules.add(addon_name) # register our conroller into the list of available controllers name_class = ("{}.{}".format(ctrl_cls.__module__, ctrl_cls.__name__), ctrl_cls) http.controllers_per_module[addon_name].append(name_class) self._apply_defaults_to_controller_routes(controller_class=ctrl_cls) def _apply_defaults_to_controller_routes(self, controller_class): """ Apply default routes properties defined on the controller_class to routes where properties are missing Set the automatic auth on controller's routes. During definition of new controller, the _default_auth should be applied on every routes (cfr @route odoo's decorator). This auth attribute should be applied only if the route doesn't already define it. :return: """ for _name, method in _inspect_methods(controller_class): routing = getattr(method, ROUTING_DECORATOR_ATTR, None) if not routing: continue self._apply_default_auth_if_not_set(controller_class, routing) self._apply_default_if_not_set(controller_class, routing, "csrf") self._apply_default_if_not_set(controller_class, routing, "save_session") self._apply_default_cors_if_not_set(controller_class, routing) def _apply_default_if_not_set(self, controller_class, routing, attr_name): default_attr_name = "_default_" + attr_name if hasattr(controller_class, default_attr_name) and attr_name not in routing: routing[attr_name] = getattr(controller_class, default_attr_name) def _apply_default_auth_if_not_set(self, controller_class, routing): default_attr_name = "_default_auth" default_auth = getattr(controller_class, default_attr_name, None) if default_auth: if "auth" in routing: auth = routing["auth"] if auth == "public_or_default": alternative_auth = "public_or_" + default_auth if getattr( self.env["ir.http"], "_auth_method_%s" % alternative_auth, None ): routing["auth"] = alternative_auth else: _logger.debug( "No %s auth method available: Fallback on %s", alternative_auth, default_auth, ) routing["auth"] = default_auth else: routing["auth"] = default_auth def _apply_default_cors_if_not_set(self, controller_class, routing): default_attr_name = "_default_cors" if hasattr(controller_class, default_attr_name) and "cors" not in routing: cors = getattr(controller_class, default_attr_name) routing["cors"] = cors if cors and "OPTIONS" not in routing.get("methods", ["OPTIONS"]): # add http method 'OPTIONS' required by cors if the route is # restricted to specific method routing["methods"].append("OPTIONS") def _get_services(self, collection_name): collection = _PseudoCollection(collection_name, self.env) work = WorkContext( model_name="rest.service.registration", collection=collection ) component_classes = work._lookup_components(usage=None, model_name=None) # removes component without collection that are not a rest service component_classes = [ c for c in component_classes if self._filter_service_component(c) ] return [comp(work) for comp in component_classes] @staticmethod def _filter_service_component(comp): return ( issubclass(comp, BaseRestService) and comp._collection and comp._usage and getattr(comp, "_is_rest_service_component", True) ) def build_registry(self, services_registry, states=None, exclude_addons=None): if not states: states = ("installed", "to upgrade") # we load REST, controllers following the order of the 'addons' # dependencies to ensure that controllers defined in a more # specialized addon and overriding more generic one takes precedences # on the generic one into the registry graph = odoo.modules.graph.Graph() graph.add_module(self.env.cr, "base") query = "SELECT name " "FROM ir_module_module " "WHERE state IN %s " params = [tuple(states)] if exclude_addons: query += " AND name NOT IN %s " params.append(tuple(exclude_addons)) self.env.cr.execute(query, params) module_list = [name for (name,) in self.env.cr.fetchall() if name not in graph] graph.add_modules(self.env.cr, module_list) for module in graph: self.load_services(module.name, services_registry) def load_services(self, module, services_registry): controller_defs = _rest_controllers_per_module.get(module, []) for controller_def in controller_defs: root_path = controller_def["root_path"] is_base_contoller = not getattr( controller_def["controller_class"], "_generated", False ) if is_base_contoller: current_controller = ( services_registry[root_path]["controller_class"] if root_path in services_registry else None ) services_registry[controller_def["root_path"]] = controller_def self._register_rest_route(controller_def["root_path"]) if ( current_controller and current_controller != controller_def["controller_class"] ): _logger.error( "Only one REST controller can be safely declared for root path %s\n " "Registering controller %s\n " "Registered controller%s\n", root_path, controller_def, services_registry[controller_def["root_path"]], ) def _init_global_registry(self): services_registry = RestServicesRegistry() _rest_services_databases[self.env.cr.dbname] = services_registry return services_registry def _register_rest_route(self, route_path): """Register given route path to be handles as RestRequest. See base_rest.http.get_request. """ _rest_services_routes[self.env.cr.dbname].add(route_path) class RestApiMethodTransformer(object): """Helper class to generate and apply the missing restapi.method decorator to service's methods defined without decorator. Before 10/12.0.3.0.0 methods exposed by a service was based on implicit conventions. This transformer is used to keep this functionality by generating and applying the missing decorators. As result all the methods exposed are decorated and the processing can be based on these decorators. """ def __init__(self, service): self._service = service def fix(self): methods_to_fix = [] for name, method in _inspect_methods(self._service.__class__): if not self._is_public_api_method(name): continue if not hasattr(method, ROUTING_DECORATOR_ATTR): methods_to_fix.append(method) for method in methods_to_fix: self._fix_method_decorator(method) def _is_public_api_method(self, method_name): if method_name.startswith("_"): return False if not hasattr(self._service, method_name): return False if hasattr(BaseRestService, method_name): # exclude methods from base class return False return True def _fix_method_decorator(self, method): method_name = method.__name__ routes = self._method_to_routes(method) input_param = self._method_to_input_param(method) output_param = self._method_to_output_param(method) decorated_method = restapi.method( routes=routes, input_param=input_param, output_param=output_param )(getattr(self._service.__class__, method_name)) setattr(self._service.__class__, method_name, decorated_method) def _method_to_routes(self, method): """ Generate the restapi.method's routes :param method: :return: A list of routes used to get access to the method """ method_name = method.__name__ signature = inspect.signature(method) id_in_path_required = "_id" in signature.parameters path = "/{}".format(method_name) if id_in_path_required: path = "/<int:id>" + path if method_name in ("get", "search"): paths = [path] path = "/" if id_in_path_required: path = "/<int:id>" paths.append(path) return [(paths, "GET")] elif method_name == "delete": routes = [(path, "POST")] path = "/" if id_in_path_required: path = "/<int:id>" routes.append((path, "DELETE")) elif method_name == "update": paths = [path] path = "/" if id_in_path_required: path = "/<int:id>" paths.append(path) routes = [(paths, "POST"), (path, "PUT")] elif method_name == "create": paths = [path] path = "/" if id_in_path_required: path = "/<int:id>" paths.append(path) routes = [(paths, "POST")] else: routes = [(path, "POST")] return routes def _method_to_param(self, validator_method_name, direction): validator_component = self._service.component(usage="cerberus.validator") if validator_component.has_validator_handler( self._service, validator_method_name, direction ): return restapi.CerberusValidator(schema=validator_method_name) return None def _method_to_input_param(self, method): validator_method_name = "_validator_{}".format(method.__name__) return self._method_to_param(validator_method_name, "input") def _method_to_output_param(self, method): validator_method_name = "_validator_return_{}".format(method.__name__) return self._method_to_param(validator_method_name, "output") class RestApiServiceControllerGenerator(object): """ An object helper used to generate the http.Controller required to serve the method decorated with the `@restappi.method` decorator """ def __init__(self, service, base_controller): self._service = service self._service_name = service._usage self._base_controller = base_controller @property def _new_cls_name(self): controller_name = self._base_controller.__name__ return "{}{}".format( controller_name, self._service._usage.title().replace(".", "_") ) def generate(self): """ :return: A new controller child of base_controller defining the routes required to serve the method of the services. """ controller = type( self._new_cls_name, (self._base_controller,), self._generate_methods() ) controller._generated = True return controller def _generate_methods(self): """Generate controller's methods and associated routes This method inspect the service definition and generate the appropriate methods and routing rules for all the methods decorated with @restappi.method :return: A dictionary of method name : method """ methods = {} _globals = {} root_path = self._base_controller._root_path path_sep = "" if root_path[-1] != "/": path_sep = "/" root_path = "{}{}{}".format(root_path, path_sep, self._service._usage) for name, method in _inspect_methods(self._service.__class__): if not hasattr(method, "routing"): continue routing = method.routing for routes, http_method in routing["routes"]: method_name = "{}_{}".format(http_method.lower(), name) default_route = routes[0] rule = Rule(default_route) Map(rules=[rule]) if rule.arguments: method = METHOD_TMPL_WITH_ARGS.format( method_name=method_name, service_name=self._service_name, service_method_name=name, args=", ".join([c[1] for c in rule._trace if c[0]]), ) else: method = METHOD_TMPL.format( method_name=method_name, service_name=self._service_name, service_method_name=name, ) exec(method, _globals) method_exec = _globals[method_name] route_params = dict( route=["{}{}".format(root_path, r) for r in routes], methods=[http_method], ) for attr in {"auth", "cors", "csrf", "save_session"}: if attr in routing: route_params[attr] = routing[attr] method_exec = http.route(**route_params)(method_exec) methods[method_name] = method_exec return methods METHOD_TMPL = """ def {method_name}(self, collection=None, **kwargs): return self._process_method( "{service_name}", "{service_method_name}", collection=collection, params=kwargs ) """ METHOD_TMPL_WITH_ARGS = """ def {method_name}(self, {args}, collection=None, **kwargs): return self._process_method( "{service_name}", "{service_method_name}", *[{args}], collection=collection, params=kwargs ) """
40
18,240
7,023
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import logging from werkzeug.exceptions import NotFound from odoo.http import request from odoo.addons.component.core import AbstractComponent from ..apispec.base_rest_service_apispec import BaseRestServiceAPISpec _logger = logging.getLogger(__name__) def to_int(val): # The javascript VM ducktape only use float and so pass float # to the api, the werkzeug request interpret params as unicode # so we have to convert params from string to float to int if isinstance(val, int): return val if val: return int(float(val)) return None def to_bool(val): return val in ("true", "True", "1", True) def skip_secure_params(func): """ Used to decorate methods :param func: :return: """ func.skip_secure_params = True return func def skip_secure_response(func): """ Used to decorate methods :param func: :return: """ func.skip_secure_response = True return func class BaseRestService(AbstractComponent): _name = "base.rest.service" _description = None # description included into the openapi doc _is_rest_service_component = True # marker to retrieve REST components def _prepare_extra_log(self, func, params, secure_params, res): httprequest = request.httprequest headers = dict(httprequest.headers) return { "application": "Rest Service", "request_url": httprequest.url, "request_method": httprequest.method, "params": params, "headers": headers, "secure_params": secure_params, "res": res, "status": 200, } def _log_call(self, func, params, secure_params, res): """If you want to enjoy the advanced log install the module logging_json""" if request: httprequest = request.httprequest extra = self._prepare_extra_log(func, params, secure_params, res) args = [httprequest.url, httprequest.method] message = "REST call url %s method %s" _logger.debug(message, *args, extra=extra) def _prepare_input_params(self, method, params): """ Internal method used to process the input_param parameter. The result will be used to call the final method. The processing is delegated to the `resapi.RestMethodParam` instance specified by the restapi.method` decorator on the method. :param method: :param params: :return: """ method_name = method.__name__ if hasattr(method, "skip_secure_params"): return params routing = getattr(method, "routing", None) if not routing: _logger.warning( "Method %s is not a public method of service %s", method_name, self._name, ) raise NotFound() input_param = routing["input_param"] if input_param: return input_param.from_params(self, params) return {} def _prepare_response(self, method, result): """ Internal method used to process the result of the method called by the controller. The result of this process is returned to the controller The processing is delegated to the `resapi.RestMethodParam` instance specified by the `restapi.method` decorator on the method. :param method: method :param response: :return: dict/json or `http.Response` """ method_name = method if callable(method): method_name = method.__name__ if hasattr(method, "skip_secure_response"): return result routing = getattr(method, "routing", None) output_param = routing["output_param"] if not output_param: _logger.warning( "DEPRECATED: You must define an output schema for method %s " "in service %s", method_name, self._name, ) return result return output_param.to_response(self, result) def dispatch(self, method_name, *args, params=None): """ This method dispatch the call to the final method. Before the call parameters are processed by the `restapi.RestMethodParam` object specified as input_param object. The result of the method is therefore given to the `restapi.RestMethodParam` object specified as output_param to build the final response returned by the service :param method_name: :param *args: query path paramters args :param params: A dictionary with the parameters of the method. Once secured and sanitized, these parameters will be passed to the method as keyword args. :return: """ method = getattr(self, method_name, object()) params = params or {} secure_params = self._prepare_input_params(method, params) if isinstance(secure_params, dict): # for backward compatibility methods expecting json params # are declared as m(self, p1=None, p2=None) or m(self, **params) res = method(*args, **secure_params) else: res = method(*args, secure_params) self._log_call(method, params, secure_params, res) return self._prepare_response(method, res) def _validator_delete(self): """ Default validator for delete method. By default delete should never be called with parameters. """ return {} def _validator_get(self): """ Default validator for get method. By default get should not be called with parameters. """ return {} def _get_api_spec(self, **params): return BaseRestServiceAPISpec(self, **params) def to_openapi(self, **params): """ Return the description of this REST service as an OpenAPI json document :return: json document """ api_spec = self._get_api_spec(**params) api_spec.generate_paths() return api_spec.to_dict() def _get_openapi_default_parameters(self): return [] def _get_openapi_default_responses(self): return { "400": {"description": "One of the given parameter is not valid"}, "401": { "description": "The user is not authorized. Authentication " "is required" }, "404": {"description": "Requested resource not found"}, "403": { "description": "You don't have the permission to access the " "requested resource." }, } @property def request(self): return self.work.request @property def controller(self): return self.work.controller
32.971831
7,023
816
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.component.core import Component class BaseRestServiceContextProvider(Component): _name = "base.rest.service.context.provider" _usage = "component_context_provider" def __init__(self, work_context): super().__init__(work_context) self.request = work_context.request # pylint: disable=assignment-from-none self.authenticated_partner_id = self._get_authenticated_partner_id() def _get_authenticated_partner_id(self): return None def _get_component_context(self): return { "request": self.request, "authenticated_partner_id": self.authenticated_partner_id, "collection": self.collection, }
31.384615
816
2,004
py
PYTHON
15.0
# Copyright 2021 Camptocamp # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.component.core import Component class BaseRestCerberusValidator(Component): """Component used to lookup the input/output validator methods To modify in your services collection:: class MyCollectionRestCerberusValidator(Component): _name = "mycollection.rest.cerberus.validator" _inherit = "base.rest.cerberus.validator" _usage = "cerberus.validator" _collection = "mycollection" def get_validator_handler(self, service, method_name, direction): # customize def has_validator_handler(self, service, method_name, direction): # customize """ _name = "base.rest.cerberus.validator" _usage = "cerberus.validator" _is_rest_service_component = False # marker to retrieve REST components def get_validator_handler(self, service, method_name, direction): """Get the validator handler for a method By default, it returns the method on the current service instance. It can be customized to delegate the validators to another component. The returned method will be called without arguments, and is expected to return the schema. direction is either "input" for request schema or "output" for responses. """ return getattr(service, method_name) def has_validator_handler(self, service, method_name, direction): """Return if the service has a validator handler for a method By default, it returns True if the the method exists on the service. It can be customized to delegate the validators to another component. The returned method will be called without arguments, and is expected to return the schema. direction is either "input" for request schema or "output" for responses. """ return hasattr(service, method_name)
37.811321
2,004
370
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.component.core import AbstractComponent class AbstractUserAuthenticatedPartnerProvider(AbstractComponent): _name = "abstract.user.authenticated.partner.provider" def _get_authenticated_partner_id(self): return self.env.user.partner_id.id
30.833333
370
4,427
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import json from contextlib import contextmanager from odoo.http import Controller, request, route from odoo.addons.component.core import WorkContext from ..core import _rest_services_databases from .main import _PseudoCollection class ApiDocsController(Controller): def make_json_response(self, data, headers=None, cookies=None): data = json.dumps(data) if headers is None: headers = {} headers["Content-Type"] = "application/json" return request.make_response(data, headers=headers, cookies=cookies) @route( ["/api-docs", "/api-docs/index.html"], methods=["GET"], type="http", auth="public", ) def index(self, **params): self._get_api_urls() primary_name = params.get("urls.primaryName") swagger_settings = { "urls": self._get_api_urls(), "urls.primaryName": primary_name, } values = {"swagger_settings": swagger_settings} return request.render("base_rest.openapi", values) @route("/api-docs/<path:collection>/<string:service_name>.json", auth="public") def api(self, collection, service_name): with self.service_and_controller_class(collection, service_name) as ( service, controller_class, ): openapi_doc = service.to_openapi( default_auth=controller_class._default_auth ) return self.make_json_response(openapi_doc) def _get_api_urls(self): """ This method lookup into the dictionary of registered REST service for the current database to built the list of available REST API :return: """ services_registry = _rest_services_databases.get(request.env.cr.dbname, {}) api_urls = [] for rest_root_path, spec in list(services_registry.items()): collection_path = rest_root_path[1:-1] # remove '/' collection_name = spec["collection_name"] for service in self._get_service_in_collection(collection_name): api_urls.append( { "name": "{}: {}".format(collection_path, service._usage), "url": "/api-docs/%s/%s.json" % (collection_path, service._usage), } ) api_urls = sorted(api_urls, key=lambda k: k["name"]) return api_urls def _filter_service_components(self, components): reg_model = request.env["rest.service.registration"] return [c for c in components if reg_model._filter_service_component(c)] def _get_service_in_collection(self, collection_name): with self.work_on_component(collection_name) as work: components = work.components_registry.lookup(collection_name) services = self._filter_service_components(components) services = [work.component(usage=s._usage) for s in services] return services @contextmanager def service_and_controller_class(self, collection_path, service_name): """ Return the component that implements the methods of the requested service. :param collection_path: :param service_name: :return: an instance of invader.service component, the base controller class serving the service """ services_spec = self._get_services_specs(collection_path) collection_name = services_spec["collection_name"] controller_class = services_spec["controller_class"] with self.work_on_component(collection_name) as work: service = work.component(usage=service_name) yield service, controller_class @contextmanager def work_on_component(self, collection_name): """ Return the all the components implementing REST services :param collection_name: :return: a WorkContext instance """ collection = _PseudoCollection(collection_name, request.env) yield WorkContext(model_name="rest.service.registration", collection=collection) def _get_services_specs(self, path): services_registry = _rest_services_databases.get(request.env.cr.dbname, {}) return services_registry["/" + path + "/"]
39.176991
4,427
7,844
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from contextlib import contextmanager from werkzeug.exceptions import BadRequest from odoo import models from odoo.http import Controller, ControllerType, Response, request from odoo.addons.component.core import WorkContext, _get_addon_name from ..core import _rest_controllers_per_module _logger = logging.getLogger(__name__) class _PseudoCollection(object): __slots__ = "_name", "env", "id" def __init__(self, name, env): self._name = name self.env = env self.id = None class RestControllerType(ControllerType): # pylint: disable=E0213 def __init__(cls, name, bases, attrs): # noqa: B902 if ( "RestController" in globals() and RestController in bases and Controller not in bases ): # to be registered as a controller into the ControllerType, # our RestConrtroller must be a direct child of Controller bases += (Controller,) super(RestControllerType, cls).__init__(name, bases, attrs) if "RestController" not in globals() or not any( issubclass(b, RestController) for b in bases ): return # register the rest controller into the rest controllers registry root_path = getattr(cls, "_root_path", None) collection_name = getattr(cls, "_collection_name", None) if root_path and collection_name: cls._module = _get_addon_name(cls.__module__) _rest_controllers_per_module[cls._module].append( { "root_path": root_path, "collection_name": collection_name, "controller_class": cls, } ) _logger.debug( "Added rest controller %s for module %s", _rest_controllers_per_module[cls._module][-1], cls._module, ) class RestController(Controller, metaclass=RestControllerType): """Generic REST Controller This controller is the base controller used by as base controller for all the REST controller generated from the service components. You must inherit of this controller into your code to register the root path used to serve all the services defined for the given collection name. This registration requires 2 parameters: _root_path: _collection_name: Only one controller by _collection_name, _root_path should exists into an odoo database. If more than one controller exists, a warning is issued into the log at startup and the concrete controller used as base class for the services registered into the collection name and served at the root path is not predictable. Module A: class ControllerA(RestController): _root_path='/my_path/' _collection_name='my_services_collection' Module B depends A: A class ControllerB(ControllerA): / \ pass B C / Module C depends A: D class ControllerC(ControllerA): pass Module D depends B: class ControllerB(ControllerB): pass In the preceding illustration, services in module C will never be served by controller D or B. Therefore if the generic dispatch method is overridden in B or D, this override wil never apply to services in C since in Odoo controllers are not designed to be inherited. That's why it's an error to have more than one controller registered for the same root path and collection name. The following properties can be specified to define common properties to apply to generated REST routes. _default_auth: The default authentication to apply to all pre defined routes. default: 'user' _default_cors: The default Access-Control-Allow-Origin cors directive value. default: None _default_csrf: Whether CSRF protection should be enabled for the route. default: False _default_save_session: Whether session should be saved into the session store default: True """ _root_path = None _collection_name = None # The default authentication to apply to all pre defined routes. _default_auth = "user" # The default Access-Control-Allow-Origin cors directive value. _default_cors = None # Whether CSRF protection should be enabled for the route. _default_csrf = False # Whether session should be saved into the session store _default_save_session = True _component_context_provider = "component_context_provider" def _get_component_context(self, collection=None): """ This method can be inherited to add parameter into the component context :return: dict of key value. """ work = WorkContext( model_name="rest.service.registration", collection=collection or self.default_collection, request=request, controller=self, ) provider = work.component(usage=self._component_context_provider) return provider._get_component_context() def make_response(self, data): if isinstance(data, Response): # The response has been build by the called method... return data # By default return result as json return request.make_json_response(data) @property def collection_name(self): return self._collection_name @property def default_collection(self): return _PseudoCollection(self.collection_name, request.env) @contextmanager def work_on_component(self, collection=None): """ Return the component that implements the methods of the requested service. :param service_name: :return: an instance of base.rest.service component """ collection = collection or self.default_collection component_ctx = self._get_component_context(collection=collection) env = collection.env collection.env = env( context=dict( env.context, authenticated_partner_id=component_ctx.get("authenticated_partner_id"), ) ) yield WorkContext(model_name="rest.service.registration", **component_ctx) @contextmanager def service_component(self, service_name, collection=None): """ Return the component that implements the methods of the requested service. :param service_name: :return: an instance of base.rest.service component """ with self.work_on_component(collection=collection) as work: service = work.component(usage=service_name) yield service def _validate_method_name(self, method_name): if method_name.startswith("_"): _logger.error( "REST API called with an unallowed method " "name: %s.\n Method can't start with '_'", method_name, ) raise BadRequest() return True def _process_method( self, service_name, method_name, *args, collection=None, params=None ): self._validate_method_name(method_name) if isinstance(collection, models.Model) and not collection: raise request.not_found() with self.service_component(service_name, collection=collection) as service: result = service.dispatch(method_name, *args, params=params) return self.make_response(result)
37
7,844
2,632
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import inspect import textwrap from apispec import APISpec from ..core import _rest_services_databases from .rest_method_param_plugin import RestMethodParamPlugin from .rest_method_security_plugin import RestMethodSecurityPlugin from .restapi_method_route_plugin import RestApiMethodRoutePlugin class BaseRestServiceAPISpec(APISpec): """ APISpec object from base.rest.service component """ def __init__(self, service_component, **params): self._service = service_component super(BaseRestServiceAPISpec, self).__init__( title="%s REST services" % self._service._usage, version="", openapi_version="3.0.0", info={ "description": textwrap.dedent( getattr(self._service, "_description", "") or "" ) }, servers=self._get_servers(), plugins=self._get_plugins(), ) self._params = params def _get_servers(self): env = self._service.env services_registry = _rest_services_databases.get(env.cr.dbname, {}) collection_path = "" for path, spec in list(services_registry.items()): if spec["collection_name"] == self._service._collection: collection_path = path break base_url = env["ir.config_parameter"].sudo().get_param("web.base.url") return [ { "url": "%s/%s/%s" % ( base_url.strip("/"), collection_path.strip("/"), self._service._usage, ) } ] def _get_plugins(self): return [ RestApiMethodRoutePlugin(self._service), RestMethodParamPlugin(self._service), RestMethodSecurityPlugin(self._service), ] def _add_method_path(self, method): description = textwrap.dedent(method.__doc__ or "") routing = method.routing for paths, method in routing["routes"]: for path in paths: self.path( path, operations={method.lower(): {"summary": description}}, routing=routing, ) def generate_paths(self): for _name, method in inspect.getmembers(self._service, inspect.ismethod): routing = getattr(method, "routing", None) if not routing: continue self._add_method_path(method)
33.316456
2,632
1,986
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import re import werkzeug.routing from apispec import BasePlugin from werkzeug.routing import Map, Rule # from flask-restplus RE_URL = re.compile(r"<(?:[^:<>]+:)?([^<>]+)>") DEFAULT_CONVERTER_MAPPING = { werkzeug.routing.UnicodeConverter: ("string", None), werkzeug.routing.IntegerConverter: ("integer", "int32"), werkzeug.routing.FloatConverter: ("number", "float"), werkzeug.routing.UUIDConverter: ("string", "uuid"), } DEFAULT_TYPE = ("string", None) class RestApiMethodRoutePlugin(BasePlugin): """ APISpec plugin to generate path from a restapi.method route """ def __init__(self, service): super(RestApiMethodRoutePlugin, self).__init__() self.converter_mapping = dict(DEFAULT_CONVERTER_MAPPING) self._service = service @staticmethod def route2openapi(path): """Convert an odoo route to an OpenAPI-compliant path. :param str path: Odoo route path template. """ return RE_URL.sub(r"{\1}", path) # Greatly inspired by flask-apispec def route_to_params(self, route): """Get parameters from Odoo route""" # odoo route are Werkzeug Rule rule = Rule(route) Map(rules=[rule]) params = [] for argument in rule.arguments: param = {"in": "path", "name": argument, "required": True} type_, format_ = self.converter_mapping.get( type(rule._converters[argument]), DEFAULT_TYPE ) schema = {"type": type_} if format_ is not None: schema["format"] = format_ param["schema"] = schema params.append(param) return params def path_helper(self, path, operations, parameters, **kwargs): for param in self.route_to_params(path): parameters.append(param) return self.route2openapi(path)
32.032258
1,986
1,382
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from apispec import BasePlugin class RestMethodSecurityPlugin(BasePlugin): """ APISpec plugin to generate path security from a services method """ def __init__(self, service, user_auths=("user",)): super(RestMethodSecurityPlugin, self).__init__() self._service = service self._supported_user_auths = user_auths # pylint: disable=W8110 def init_spec(self, spec): super(RestMethodSecurityPlugin, self).init_spec(spec) self.spec = spec self.openapi_version = spec.openapi_version user_scheme = {"type": "apiKey", "in": "cookie", "name": "session_id"} spec.components.security_scheme("user", user_scheme) def operation_helper(self, path=None, operations=None, **kwargs): routing = kwargs.get("routing") if not routing: super(RestMethodSecurityPlugin, self).operation_helper( path, operations, **kwargs ) if not operations: return auth = routing.get("auth", self.spec._params.get("default_auth")) if auth in self._supported_user_auths: for _method, params in operations.items(): security = params.setdefault("security", []) security.append({"user": []})
37.351351
1,382
3,147
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from apispec import BasePlugin from ..restapi import RestMethodParam class RestMethodParamPlugin(BasePlugin): """ APISpec plugin to generate path parameters and responses from a services method """ def __init__(self, service): super(RestMethodParamPlugin, self).__init__() self._service = service self._default_parameters = service._get_openapi_default_parameters() self._default_responses = service._get_openapi_default_responses() # pylint: disable=W8110 def init_spec(self, spec): super(RestMethodParamPlugin, self).init_spec(spec) self.spec = spec self.openapi_version = spec.openapi_version def operation_helper(self, path=None, operations=None, **kwargs): routing = kwargs.get("routing") if not routing: super(RestMethodParamPlugin, self).operation_helper( path, operations, **kwargs ) if not operations: return for method, params in operations.items(): parameters = self._generate_pamareters(routing, method, params) if parameters: params["parameters"] = parameters responses = self._generate_responses(routing, method, params) if responses: params["responses"] = responses def _generate_pamareters(self, routing, method, params): parameters = params.get("parameters", []) # add default paramters provided by the sevice parameters.extend(self._default_parameters) input_param = routing.get("input_param") if input_param and isinstance(input_param, RestMethodParam): if method == "get": # get quey params from RequestMethodParam object parameters.extend( input_param.to_openapi_query_parameters(self._service, self.spec) ) else: # get requestBody from RequestMethodParam object request_body = params.get("requestBody", {}) request_body.update( input_param.to_openapi_requestbody(self._service, self.spec) ) params["requestBody"] = request_body # sort paramters to ease comparison into unittests parameters.sort(key=lambda a: a["name"]) return parameters def _generate_responses(self, routing, method, params): responses = params.get("responses", {}) # add default responses provided by the service responses.update(self._default_responses.copy()) output_param = routing.get("output_param") if output_param and isinstance(output_param, RestMethodParam): responses = params.get("responses", {}) # get response from RequestMethodParam object responses.update(self._default_responses.copy()) responses.update( output_param.to_openapi_responses(self._service, self.spec) ) return responses
40.87013
3,147
552
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Base Rest Datamodel", "summary": """ Pydantic binding for base_rest""", "version": "15.0.4.3.1", "license": "LGPL-3", "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/rest-framework", "depends": ["base_rest"], "data": [], "demo": [], "installable": True, "external_dependencies": { "python": [ "pydantic", ] }, }
26.285714
552
8,122
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import _ from odoo.exceptions import UserError from odoo.addons.base_rest import restapi from pydantic import BaseModel, ValidationError, validate_model def replace_ref_in_schema(item, original_schema): if isinstance(item, list): return [replace_ref_in_schema(i, original_schema) for i in item] elif isinstance(item, dict): if list(item.keys()) == ["$ref"]: schema = item["$ref"].split("/")[-1] return {"$ref": f"#/components/schemas/{schema}"} else: return { key: replace_ref_in_schema(i, original_schema) for key, i in item.items() } else: return item class PydanticModel(restapi.RestMethodParam): def __init__(self, cls: BaseModel): """ :param name: The pydantic model name """ if not issubclass(cls, BaseModel): raise TypeError( f"{cls} is not a subclass of odoo.addons.pydantic.models.BaseModel" ) self._model_cls = cls def from_params(self, service, params): try: return self._model_cls(**params) except ValidationError as ve: raise UserError(_("BadRequest %s") % ve.json(indent=0)) from ve def to_response(self, service, result): # do we really need to validate the instance???? json_dict = result.dict() to_validate = ( json_dict if not result.__config__.orm_mode else result.dict(by_alias=True) ) *_, validation_error = validate_model(self._model_cls, to_validate) if validation_error: raise SystemError(_("Invalid Response %s") % validation_error) return json_dict def to_openapi_query_parameters(self, servic, spec): json_schema = self._model_cls.schema() parameters = [] for prop, spec in list(json_schema["properties"].items()): params = { "name": prop, "in": "query", "required": prop in json_schema.get("required", []), "allowEmptyValue": spec.get("nullable", False), "default": spec.get("default"), } if spec.get("schema"): params["schema"] = spec.get("schema") else: params["schema"] = {"type": spec["type"]} if spec.get("items"): params["schema"]["items"] = spec.get("items") if "enum" in spec: params["schema"]["enum"] = spec["enum"] parameters.append(params) if spec["type"] == "array": # To correctly handle array into the url query string, # the name must ends with [] params["name"] = params["name"] + "[]" return parameters # TODO, we should probably get the spec as parameters. That should # allows to add the definition of a schema only once into the specs # and use a reference to the schema into the parameters def to_openapi_requestbody(self, service, spec): return { "content": { "application/json": { "schema": self.to_json_schema(service, spec, "input") } } } def to_openapi_responses(self, service, spec): return { "200": { "content": { "application/json": { "schema": self.to_json_schema(service, spec, "output") } } } } def to_json_schema(self, service, spec, direction): schema = self._model_cls.schema() schema_name = schema["title"] if schema_name not in spec.components.schemas: definitions = schema.get("definitions", {}) for name, sch in definitions.items(): if name in spec.components.schemas: continue sch = replace_ref_in_schema(sch, sch) spec.components.schema(name, sch) schema = replace_ref_in_schema(schema, schema) spec.components.schema(schema_name, schema) return {"$ref": f"#/components/schemas/{schema_name}"} class PydanticModelList(PydanticModel): def __init__( self, cls: BaseModel, min_items: int = None, max_items: int = None, unique_items: bool = None, ): """ :param name: The pydantic model name :param min_items: A list instance is valid against "min_items" if its size is greater than, or equal to, min_items. The value MUST be a non-negative integer. :param max_items: A list instance is valid against "max_items" if its size is less than, or equal to, max_items. The value MUST be a non-negative integer. :param unique_items: Used to document that the list should only contain unique items. (Not enforced at validation time) """ super().__init__(cls=cls) self._min_items = min_items self._max_items = max_items self._unique_items = unique_items def from_params(self, service, params): self._do_validate(params, "input") return [ super(PydanticModelList, self).from_params(service, param) for param in params ] def to_response(self, service, result): self._do_validate(result, "output") return [ super(PydanticModelList, self).to_response(service=service, result=r) for r in result ] def to_openapi_query_parameters(self, service, spec): raise NotImplementedError("List are not (?yet?) supported as query paramters") def _do_validate(self, values, direction): ExceptionClass = UserError if direction == "input" else SystemError if self._min_items is not None and len(values) < self._min_items: raise ExceptionClass( _( "BadRequest: Not enough items in the list (%(current)s < %(expected)s)", current=len(values), expected=self._min_items, ) ) if self._max_items is not None and len(values) > self._max_items: raise ExceptionClass( _( "BadRequest: Too many items in the list (%(current)s > %(expected)s)", current=len(values), expected=self._max_items, ) ) # TODO, we should probably get the spec as parameters. That should # allows to add the definition of a schema only once into the specs # and use a reference to the schema into the parameters def to_openapi_requestbody(self, service, spec): return { "content": { "application/json": { "schema": self.to_json_schema(service, spec, "input") } } } def to_openapi_responses(self, service, spec): return { "200": { "content": { "application/json": { "schema": self.to_json_schema(service, spec, "output") } } } } def to_json_schema(self, service, spec, direction): json_schema = super().to_json_schema(service, spec, direction) json_schema = {"type": "array", "items": json_schema} if self._min_items is not None: json_schema["minItems"] = self._min_items if self._max_items is not None: json_schema["maxItems"] = self._max_items if self._unique_items is not None: json_schema["uniqueItems"] = self._unique_items return json_schema restapi.PydanticModel = PydanticModel restapi.PydanticModelList = PydanticModelList
36.918182
8,122
2,233
py
PYTHON
15.0
# Copyright 2021 Wakari SRL # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from typing import Type import mock from odoo.exceptions import UserError from odoo.tests.common import TransactionCase from pydantic import BaseModel from .. import restapi class TestPydantic(TransactionCase): def setUp(self): super(TestPydantic, self).setUp() class Model1(BaseModel): name: str description: str = None self.Model1: BaseModel = Model1 def _from_params(self, pydantic_cls: Type[BaseModel], params: dict, **kwargs): restapi_pydantic_cls = ( restapi.PydanticModelList if isinstance(params, list) else restapi.PydanticModel ) restapi_pydantic = restapi_pydantic_cls(pydantic_cls, **kwargs) mock_service = mock.Mock() mock_service.env = self.env return restapi_pydantic.from_params(mock_service, params) def test_from_params(self): params = {"name": "Instance Name", "description": "Instance Description"} instance = self._from_params(self.Model1, params) self.assertEqual(instance.name, params["name"]) self.assertEqual(instance.description, params["description"]) def test_from_params_missing_optional_field(self): params = {"name": "Instance Name"} instance = self._from_params(self.Model1, params) self.assertEqual(instance.name, params["name"]) self.assertIsNone(instance.description) def test_from_params_missing_required_field(self): msg = r"value_error.missing" with self.assertRaisesRegex(UserError, msg): self._from_params(self.Model1, {"description": "Instance Description"}) def test_from_params_pydantic_model_list(self): params = [ {"name": "Instance Name", "description": "Instance Description"}, {"name": "Instance Name 2", "description": "Instance Description 2"}, ] instances = self._from_params(self.Model1, params) self.assertEqual(len(instances), 2) self.assertEqual(instances[0].name, params[0]["name"]) self.assertEqual(instances[0].description, params[0]["description"])
36.606557
2,233
1,372
py
PYTHON
15.0
# Copyright 2021 Wakari SRL # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from typing import List import mock from odoo.tests.common import TransactionCase from pydantic import BaseModel from .. import restapi class TestPydantic(TransactionCase): def _to_response(self, instance: BaseModel): restapi_pydantic = restapi.PydanticModel(instance.__class__) mock_service = mock.Mock() mock_service.env = self.env return restapi_pydantic.to_response(mock_service, instance) def _to_response_list(self, instance: List[BaseModel]): restapi_pydantic = restapi.PydanticModelList(instance[0].__class__) mock_service = mock.Mock() mock_service.env = self.env return restapi_pydantic.to_response(mock_service, instance) def test_to_response(self): class Model1(BaseModel): name: str instance = Model1(name="Instance 1") res = self._to_response(instance) self.assertEqual(res["name"], instance.name) def test_to_response_list(self): class Model1(BaseModel): name: str instances = (Model1(name="Instance 1"), Model1(name="Instance 2")) res = self._to_response_list(instances) self.assertEqual(len(res), 2) self.assertSetEqual({r["name"] for r in res}, {"Instance 1", "Instance 2"})
32.666667
1,372
641
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Pydantic", "summary": """ Utility addon to ease mapping between Pydantic and Odoo models""", "version": "15.0.1.1.1", "development_status": "Beta", "license": "LGPL-3", "maintainers": ["lmignon"], "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/rest-framework", "depends": [], "data": [], "demo": [], "external_dependencies": { "python": ["pydantic", "contextvars", "typing-extensions"] }, "installable": True, }
30.52381
641
2,221
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from typing import Any from odoo import fields, models from pydantic.utils import GetterDict class GenericOdooGetter(GetterDict): """A generic GetterDict for Odoo models The getter take care of casting one2many and many2many field values to python list to allow the from_orm method from pydantic class to work on odoo models. This getter is to specify into the pydantic config. Usage: .. code-block:: python import pydantic from odoo.addons.pydantic import models, utils class Group(models.BaseModel): name: str class Config: orm_mode = True getter_dict = utils.GenericOdooGetter class UserInfo(models.BaseModel): name: str groups: List[Group] = pydantic.Field(alias="groups_id") class Config: orm_mode = True getter_dict = utils.GenericOdooGetter user = self.env.user user_info = UserInfo.from_orm(user) To avoid having to repeat the specific configuration required for the `from_orm` method into each pydantic model, "odoo_orm_mode" can be used as parent via the `_inherit` attribute """ def get(self, key: Any, default: Any = None) -> Any: res = getattr(self._obj, key, default) if isinstance(self._obj, models.BaseModel) and key in self._obj._fields: field = self._obj._fields[key] if res is False and field.type != "boolean": return None if field.type == "date" and not res: return None if field.type == "datetime": if not res: return None # Get the timestamp converted to the client's timezone. # This call also add the tzinfo into the datetime object return fields.Datetime.context_timestamp(self._obj, res) if field.type == "many2one" and not res: return None if field.type in ["one2many", "many2many"]: return list(res) return res
32.661765
2,221
1,439
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Fields ===== Create a single place for all fields defined for datamodels """ import logging from .core import Datamodel _logger = logging.getLogger(__name__) try: from marshmallow.fields import * # noqa: F403,F401 from marshmallow.fields import Nested except ImportError: Nested = object _logger.debug("Cannot import 'marshmallow'.") class NestedModel(Nested): def __init__(self, nested, **kwargs): self.datamodel_name = nested super(NestedModel, self).__init__(None, **kwargs) @property def schema(self): if not self.nested: # Get the major parent to avoid error of _env does not exist super_parent = None parent = self while not super_parent: if not hasattr(parent, "parent"): super_parent = parent break parent = parent.parent self.nested = super_parent._env.datamodels[ self.datamodel_name ].__schema_class__ self.nested._env = super_parent._env return super(NestedModel, self).schema def _deserialize(self, value, attr, data, **kwargs): if isinstance(value, Datamodel): return value return super(NestedModel, self)._deserialize(value, attr, data, **kwargs)
28.78
1,439
15,067
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import logging from collections import OrderedDict, defaultdict from contextlib import ExitStack from marshmallow import INCLUDE from odoo.api import Environment from odoo.tools import LastOrderedSet, OrderedSet _logger = logging.getLogger(__name__) try: import marshmallow from marshmallow_objects.models import Model as MarshmallowModel, ModelMeta except ImportError: _logger.debug("Cannot import 'marshmallow_objects'.") # The Cache size represents the number of items, so the number # of datamodels (include abstract datamodels) we will keep in the LRU # cache. We would need stats to know what is the average but this is a bit # early. DEFAULT_CACHE_SIZE = 512 # this is duplicated from odoo.models.MetaModel._get_addon_name() which we # unfortunately can't use because it's an instance method and should have been # a @staticmethod def _get_addon_name(full_name): # The (Odoo) module name can be in the ``odoo.addons`` namespace # or not. For instance, module ``sale`` can be imported as # ``odoo.addons.sale`` (the right way) or ``sale`` (for backward # compatibility). module_parts = full_name.split(".") if len(module_parts) > 2 and module_parts[:2] == ["odoo", "addons"]: addon_name = module_parts[2] else: addon_name = module_parts[0] return addon_name def _get_nested_schemas(schema): res = [schema] for field in schema.fields.values(): if getattr(field, "schema", None): res += _get_nested_schemas(field.schema) return res class DatamodelDatabases(dict): """Holds a registry of datamodels for each database""" class DatamodelRegistry(object): """Store all the datamodel and allow to retrieve them by name The key is the ``_name`` of the datamodels. This is an OrderedDict, because we want to keep the registration order of the datamodels, addons loaded first have their datamodels found first. The :attr:`ready` attribute must be set to ``True`` when all the datamodels are loaded. """ def __init__(self, cachesize=DEFAULT_CACHE_SIZE): self._datamodels = OrderedDict() self._loaded_modules = set() self.ready = False def __getitem__(self, key): return self._datamodels[key] def __setitem__(self, key, value): self._datamodels[key] = value def __contains__(self, key): return key in self._datamodels def get(self, key, default=None): return self._datamodels.get(key, default) def __iter__(self): return iter(self._datamodels) def load_datamodels(self, module): if module in self._loaded_modules: return for datamodel_class in MetaDatamodel._modules_datamodels[module]: datamodel_class._build_datamodel(self) self._loaded_modules.add(module) # We will store a DatamodeltRegistry per database here, # it will be cleared and updated when the odoo's registry is rebuilt _datamodel_databases = DatamodelDatabases() @marshmallow.post_load def __make_object__(self, data, **kwargs): datamodel = self._env.datamodels[self._datamodel_name] return datamodel(__post_load__=True, __schema__=self, **data) class MetaDatamodel(ModelMeta): """Metaclass for Datamodel Every new :class:`Datamodel` will be added to ``_modules_datamodels``, that will be used by the datamodel builder. """ _modules_datamodels = defaultdict(list) def __init__(self, name, bases, attrs): if not self._register: self._register = True super(MetaDatamodel, self).__init__(name, bases, attrs) return # If datamodels are declared in tests, exclude them from the # "datamodels of the addon" list. If not, when we use the # "load_datamodels" method, all the test datamodels would be loaded. # This should never be an issue when running the app normally, as the # Python tests should never be executed. But this is an issue when a # test creates a test datamodels for the purpose of the test, then a # second tests uses the "load_datamodels" to load all the addons of the # module: it will load the datamodel of the previous test. if "tests" in self.__module__.split("."): return if not hasattr(self, "_module"): self._module = _get_addon_name(self.__module__) self._modules_datamodels[self._module].append(self) def __call__(self, *args, **kwargs): """Allow to set any field (including 'dump_only') at instantiation This is not an issue thanks to cleanup during (de)serialization """ kwargs["unknown"] = kwargs.get("unknown", INCLUDE) return super().__call__(*args, **kwargs) class Datamodel(MarshmallowModel, metaclass=MetaDatamodel): """Main Datamodel Model All datamodels have a Python inheritance either on :class:`Datamodel`. Inheritance mechanism The inheritance mechanism is like the Odoo's one for Models. Each datamodel has a ``_name``. This is the absolute minimum in a Datamodel class. :: from marshmallow import fields from odoo.addons.datamodel.core import Datamodel class MyDatamodel(Datamodel): _name = 'my.datamodel' name = fields.String() Every datamodel implicitly inherit from the `'base'` datamodel. There are two close but distinct inheritance types, which look familiar if you already know Odoo. The first uses ``_inherit`` with an existing name, the name of the datamodel we want to extend. With the following example, ``my.datamodel`` is now able to speak and to yell. :: class MyDatamodel(Datamodel): # name of the class does not matter _inherit = 'my.datamodel' The second has a different ``_name``, it creates a new datamodel, including the behavior of the inherited datamodel, but without modifying it. :: class AnotherDatamodel(Datamodel): _name = 'another.datamodel' _inherit = 'my.datamodel' age = fields.Int() """ _register = False _env = None # Odoo Environment # used for inheritance _name = None #: Name of the datamodel #: Name or list of names of the datamodel(s) to inherit from _inherit = None def __init__(self, context=None, partial=None, env=None, **kwargs): self._env = env or type(self)._env super().__init__(context=context, partial=partial, **kwargs) @property def env(self): return self._env @classmethod def get_schema(cls, **kwargs): """ Get a marshmallow schema instance :param kwargs: :return: """ return cls.__get_schema_class__(**kwargs) @classmethod def validate(cls, data, context=None, many=None, partial=None, unknown=None): schema = cls.__get_schema_class__( context=context, partial=partial, unknown=unknown ) all_schemas = _get_nested_schemas(schema) with ExitStack() as stack: # propagate 'unknown' to each nested schema during validate for nested_schema in all_schemas: stack.enter_context(cls.propagate_unknwown(nested_schema, unknown)) return schema.validate(data, many=many, partial=partial) @classmethod def _build_datamodel(cls, registry): """Instantiate a given Datamodel in the datamodels registry. This method is called at the end of the Odoo's registry build. The caller is :meth:`datamodel.builder.DatamodelBuilder.load_datamodels`. It generates new classes, which will be the Datamodel classes we will be using. The new classes are generated following the inheritance of ``_inherit``. It ensures that the ``__bases__`` of the generated Datamodel classes follow the ``_inherit`` chain. Once a Datamodel class is created, it adds it in the Datamodel Registry (:class:`DatamodelRegistry`), so it will be available for lookups. At the end of new class creation, a hook method :meth:`_complete_datamodel_build` is called, so you can customize further the created datamodels. The following code is roughly the same than the Odoo's one for building Models. """ # In the simplest case, the datamodel's registry class inherits from # cls and the other classes that define the datamodel in a flat # hierarchy. The registry contains the instance ``datamodel`` (on the # left). Its class, ``DatamodelClass``, carries inferred metadata that # is shared between all the datamodel's instances for this registry # only. # # class A1(Datamodel): Datamodel # _name = 'a' / | \ # A3 A2 A1 # class A2(Datamodel): \ | / # _inherit = 'a' DatamodelClass # # class A3(Datamodel): # _inherit = 'a' # # When a datamodel is extended by '_inherit', its base classes are # modified to include the current class and the other inherited # datamodel classes. # Note that we actually inherit from other ``DatamodelClass``, so that # extensions to an inherited datamodel are immediately visible in the # current datamodel class, like in the following example: # # class A1(Datamodel): # _name = 'a' Datamodel # / / \ \ # class B1(Datamodel): / A2 A1 \ # _name = 'b' / \ / \ # B2 DatamodelA B1 # class B2(Datamodel): \ | / # _name = 'b' \ | / # _inherit = ['b', 'a'] \ | / # DatamodelB # class A2(Datamodel): # _inherit = 'a' # determine inherited datamodels parents = cls._inherit if isinstance(parents, str): parents = [parents] elif parents is None: parents = [] if cls._name in registry and not parents: raise TypeError( "Datamodel %r (in class %r) already exists. " "Consider using _inherit instead of _name " "or using a different _name." % (cls._name, cls) ) # determine the datamodel's name name = cls._name or (len(parents) == 1 and parents[0]) if not name: raise TypeError("Datamodel %r must have a _name" % cls) # all datamodels except 'base' implicitly inherit from 'base' if name != "base": parents = list(parents) + ["base"] # create or retrieve the datamodel's class if name in parents: if name not in registry: raise TypeError("Datamodel %r does not exist in registry." % name) # determine all the classes the datamodel should inherit from bases = LastOrderedSet([cls]) for parent in parents: if parent not in registry: raise TypeError( "Datamodel %r inherits from non-existing datamodel %r." % (name, parent) ) parent_class = registry[parent] if parent == name: for base in parent_class.__bases__: bases.add(base) else: bases.add(parent_class) parent_class._inherit_children.add(name) if name in parents: DatamodelClass = registry[name] # Add the new bases to the existing model since the class into # the registry could already be used into an inherit DatamodelClass.__bases__ = tuple(bases) # We must update the marshmallow schema on the existing datamodel # class to include those inherited parent_schemas = [] for parent in bases: if issubclass(parent, MarshmallowModel): parent_schemas.append(parent.__schema_class__) schema_class = type(name + "Schema", tuple(parent_schemas), {}) DatamodelClass.__schema_class__ = schema_class else: attrs = { "_name": name, "_register": False, # names of children datamodel "_inherit_children": OrderedSet(), } if name == "base": attrs["_registry"] = registry DatamodelClass = type(name, tuple(bases), attrs) setattr(DatamodelClass.__schema_class__, "_registry", registry) # noqa: B010 setattr(DatamodelClass.__schema_class__, "_datamodel_name", name) # noqa: B010 setattr( # noqa: B010 DatamodelClass.__schema_class__, "__make_object__", __make_object__ ) DatamodelClass._complete_datamodel_build() registry[name] = DatamodelClass return DatamodelClass @classmethod def _complete_datamodel_build(cls): """Complete build of the new datamodel class After the datamodel has been built from its bases, this method is called, and can be used to customize the class before it can be used. Nothing is done in the base Datamodel, but a Datamodel can inherit the method to add its own behavior. """ # makes the datamodels registry available on env class DataModelFactory(object): """Factory for datamodels This factory ensures the propagation of the environment to the instanciated datamodels and related schema. """ __slots__ = ("env", "registry") def __init__(self, env, registry): self.env = env self.registry = registry def __getitem__(self, key): model = self.registry[key] model._env = self.env @classmethod def __get_schema_class__(cls, **kwargs): cls = cls.__schema_class__(**kwargs) cls._env = self.env return cls model.__get_schema_class__ = __get_schema_class__ return model @property def datamodels(self): if not hasattr(self, "_datamodels_factory"): factory = DataModelFactory(self, _datamodel_databases.get(self.cr.dbname)) self._datamodels_factory = factory return self._datamodels_factory Environment.datamodels = datamodels
35.203271
15,067
3,689
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Datamodels Builder ================== Build the datamodels at the build of a registry. """ from odoo import models, modules from .core import DEFAULT_CACHE_SIZE, DatamodelRegistry, _datamodel_databases class DatamodelBuilder(models.AbstractModel): """Build the datamodel classes And register them in a global registry. Every time an Odoo registry is built, the know datamodels are cleared and rebuilt as well. The Datamodel classes are built using the same mechanism than Odoo's Models: a final class is created, taking every Datamodels with a ``_name`` and applying Datamodels with an ``_inherits`` upon them. The final Datamodel classes are registered in global registry. This class is an Odoo model, allowing us to hook the build of the datamodels at the end of the Odoo's registry loading, using ``_register_hook``. This method is called after all modules are loaded, so we are sure that we have all the datamodels Classes and in the correct order. """ _name = "datamodel.builder" _description = "Datamodel Builder" _datamodels_registry_cache_size = DEFAULT_CACHE_SIZE def _register_hook(self): # This method is called by Odoo when the registry is built, # so in case the registry is rebuilt (cache invalidation, ...), # we have to rebuild the datamodels. We use a new # registry so we have an empty cache and we'll add datamodels in it. datamodels_registry = self._init_global_registry() self.build_registry(datamodels_registry) datamodels_registry.ready = True def _init_global_registry(self): datamodels_registry = DatamodelRegistry( cachesize=self._datamodels_registry_cache_size ) _datamodel_databases[self.env.cr.dbname] = datamodels_registry return datamodels_registry def build_registry(self, datamodels_registry, states=None, exclude_addons=None): if not states: states = ("installed", "to upgrade") # lookup all the installed (or about to be) addons and generate # the graph, so we can load the datamodels following the order # of the addons' dependencies graph = modules.graph.Graph() graph.add_module(self.env.cr, "base") query = "SELECT name " "FROM ir_module_module " "WHERE state IN %s " params = [tuple(states)] if exclude_addons: query += " AND name NOT IN %s " params.append(tuple(exclude_addons)) self.env.cr.execute(query, params) module_list = [name for (name,) in self.env.cr.fetchall() if name not in graph] graph.add_modules(self.env.cr, module_list) for module in graph: self.load_datamodels(module.name, datamodels_registry=datamodels_registry) def load_datamodels(self, module, datamodels_registry=None): """Build every datamodel known by MetaDatamodel for an odoo module The final datamodel (composed by all the Datamodel classes in this module) will be pushed into the registry. :param module: the name of the addon for which we want to load the datamodels :type module: str | unicode :param registry: the registry in which we want to put the Datamodel :type registry: :py:class:`~.core.DatamodelRegistry` """ datamodels_registry = ( datamodels_registry or _datamodel_databases[self.env.cr.dbname] ) datamodels_registry.load_datamodels(module)
38.427083
3,689
666
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Datamodel", "summary": """ This addon allows you to define simple data models supporting serialization/deserialization""", "version": "15.0.1.0.1", "license": "LGPL-3", "development_status": "Beta", "author": "ACSONE SA/NV, " "Odoo Community Association (OCA)", "maintainers": ["lmignon"], "website": "https://github.com/OCA/rest-framework", "depends": [], "data": [], "demo": [], "external_dependencies": {"python": ["marshmallow", "marshmallow-objects>=2.0.0"]}, "installable": True, }
33.3
666
332
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from ..core import Datamodel class BaseDatamodel(Datamodel): """This is the base datamodel for every datamodel It is implicitely inherited by all datamodels. All your base are belong to us """ _name = "base"
22.133333
332
6,585
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import copy from contextlib import contextmanager import odoo from odoo import api from odoo.tests import common from ..core import ( DatamodelRegistry, MetaDatamodel, _datamodel_databases, _get_addon_name, ) @contextmanager def new_rollbacked_env(): registry = odoo.registry(common.get_db_name()) uid = odoo.SUPERUSER_ID cr = registry.cursor() try: yield api.Environment(cr, uid, {}) finally: cr.rollback() # we shouldn't have to commit anything cr.close() class DatamodelMixin(object): @classmethod def setUpDatamodel(cls): with new_rollbacked_env() as env: builder = env["datamodel.builder"] # build the datamodels of every installed addons datamodel_registry = builder._init_global_registry() cls._datamodels_registry = datamodel_registry # ensure that we load only the datamodels of the 'installed' # modules, not 'to install', which means we load only the # dependencies of the tested addons, not the siblings or # chilren addons builder.build_registry(datamodel_registry, states=("installed",)) # build the datamodels of the current tested addon current_addon = _get_addon_name(cls.__module__) env["datamodel.builder"].load_datamodels(current_addon) # pylint: disable=W8106 def setUp(self): # should be ready only during tests, never during installation # of addons self._datamodels_registry.ready = True @self.addCleanup def notready(): self._datamodels_registry.ready = False class TransactionDatamodelCase(common.TransactionCase, DatamodelMixin): """A TransactionCase that loads all the datamodels It is used like an usual Odoo's TransactionCase, but it ensures that all the datamodels of the current addon and its dependencies are loaded. """ @classmethod def setUpClass(cls): super().setUpClass() cls.setUpDatamodel() # pylint: disable=W8106 def setUp(self): # resolve an inheritance issue (common.TransactionCase does not call # super) common.TransactionCase.setUp(self) DatamodelMixin.setUp(self) class DatamodelRegistryCase( common.BaseCase, common.MetaCase("DummyCase", (object,), {}) ): """This test case can be used as a base for writings tests on datamodels This test case is meant to test datamodels in a special datamodel registry, where you want to have maximum control on which datamodels are loaded or not, or when you want to create additional datamodels in your tests. If you only want to *use* the datamodels of the tested addon in your tests, then consider using: * :class:`TransactionDatamodelCase` This test case creates a special :class:`odoo.addons.datamodel.core.DatamodelRegistry` for the purpose of the tests. By default, it loads all the datamodels of the dependencies, but not the datamodels of the current addon (which you have to handle manually). In your tests, you can add more datamodels in 2 manners. All the datamodels of an Odoo module:: self._load_module_datamodels('connector') Only specific datamodels:: self._build_datamodels(MyDatamodel1, MyDatamodel2) Note: for the lookups of the datamodels, the default datamodel registry is a global registry for the database. Here, you will need to explicitly pass ``self.datamodel_registry`` in the """ def setUp(self): super().setUp() # keep the original classes registered by the metaclass # so we'll restore them at the end of the tests, it avoid # to pollute it with Stub / Test datamodels self._original_datamodels = copy.deepcopy(MetaDatamodel._modules_datamodels) # it will be our temporary datamodel registry for our test session self.datamodel_registry = DatamodelRegistry() # it builds the 'final datamodel' for every datamodel of the # 'datamodel' addon and push them in the datamodel registry self.datamodel_registry.load_datamodels("datamodel") # build the datamodels of every installed addons already installed # but the current addon (when running with pytest/nosetest, we # simulate the --test-enable behavior by excluding the current addon # which is in 'to install' / 'to upgrade' with --test-enable). current_addon = _get_addon_name(self.__module__) registry = odoo.registry(common.get_db_name()) uid = odoo.SUPERUSER_ID cr = registry.cursor() env = api.Environment(cr, uid, {}) env["datamodel.builder"].build_registry( self.datamodel_registry, states=("installed",), exclude_addons=[current_addon], ) self.env = env _datamodel_databases[self.env.cr.dbname] = self.datamodel_registry @self.addCleanup def _close_and_roolback(): cr.rollback() # we shouldn't have to commit anything cr.close() # Fake that we are ready to work with the registry # normally, it is set to True and the end of the build # of the datamodels. Here, we'll add datamodels later in # the datamodels registry, but we don't mind for the tests. self.datamodel_registry.ready = True def tearDown(self): super().tearDown() # restore the original metaclass' classes MetaDatamodel._modules_datamodels = self._original_datamodels def _load_module_datamodels(self, module): self.datamodel_registry.load_datamodels(module) def _build_datamodels(self, *classes): for cls in classes: cls._build_datamodel(self.datamodel_registry) class TransactionDatamodelRegistryCase(common.TransactionCase, DatamodelRegistryCase): """Adds Odoo Transaction in the base Datamodel TestCase""" # pylint: disable=W8106 @classmethod def setUpClass(cls): # resolve an inheritance issue (common.TransactionCase does not use # super) common.TransactionCase.setUpClass(cls) DatamodelRegistryCase.setUp(cls) cls.collection = cls.env["collection.base"] @classmethod def tearDownClass(cls): common.TransactionCase.tearDownClass(cls) DatamodelRegistryCase.tearDown(cls)
35.594595
6,585
16,939
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import mock from marshmallow_objects.models import Model as MarshmallowModel from odoo import SUPERUSER_ID, api from .. import fields from ..core import Datamodel from .common import DatamodelRegistryCase, TransactionDatamodelCase class TestBuildDatamodel(DatamodelRegistryCase): """Test build of datamodels All the tests in this suite are based on the same principle with variations: * Create new Datamodels (classes inheriting from :class:`datamodel.core.Datamodel` * Call :meth:`datamodel.core.Datamodel._build_datamodel` on them in order to build the 'final class' composed from all the ``_inherit`` and push it in the datamodels registry (``self.datamodel_registry`` here) * Assert that classes are built, registered, have correct ``__bases__``... """ def test_type(self): """Ensure that a datamodels are instances of marshomallow_objects.Model""" class Datamodel1(Datamodel): _name = "datamodel1" class Datamodel2(Datamodel): _name = "datamodel2" _inherit = "datamodel1" self.assertIsInstance(Datamodel1(), MarshmallowModel) self.assertIsInstance(Datamodel2(), MarshmallowModel) def test_no_name(self): """Ensure that a datamodel has a _name""" class Datamodel1(Datamodel): pass msg = ".*must have a _name.*" with self.assertRaisesRegex(TypeError, msg): Datamodel1._build_datamodel(self.datamodel_registry) def test_register(self): """Able to register datamodels in datamodels registry""" class Datamodel1(Datamodel): _name = "datamodel1" class Datamodel2(Datamodel): _name = "datamodel2" # build the 'final classes' for the datamodels and check that we find # them in the datamodels registry Datamodel1._build_datamodel(self.datamodel_registry) Datamodel2._build_datamodel(self.datamodel_registry) self.assertEqual( ["base", "datamodel1", "datamodel2"], list(self.datamodel_registry) ) # pylint: disable=R7980 def test_inherit_bases(self): """Check __bases__ of Datamodel with _inherit""" class Datamodel1(Datamodel): _name = "datamodel1" field_str1 = fields.String(load_default="field_str1") class Datamodel2(Datamodel): _inherit = "datamodel1" field_str2 = fields.String(load_default="field_str2") class Datamodel3(Datamodel): _inherit = "datamodel1" field_str3 = fields.String(load_default="field_str3") Datamodel1._build_datamodel(self.datamodel_registry) Datamodel2._build_datamodel(self.datamodel_registry) Datamodel3._build_datamodel(self.datamodel_registry) self.assertEqual( (Datamodel3, Datamodel2, Datamodel1, self.env.datamodels["base"]), self.env.datamodels["datamodel1"].__bases__, ) def test_prototype_inherit_bases(self): """Check __bases__ of Datamodel with _inherit and different _name""" class Datamodel1(Datamodel): _name = "datamodel1" field_int = fields.Int(load_default=1) class Datamodel2(Datamodel): _name = "datamodel2" _inherit = "datamodel1" field_boolean = fields.Boolean(load_default=True) field_int = fields.Int(load_default=2) class Datamodel3(Datamodel): _name = "datamodel3" _inherit = "datamodel1" field_float = fields.Float(load_default=0.3) class Datamodel4(Datamodel): _name = "datamodel4" _inherit = ["datamodel2", "datamodel3"] Datamodel1._build_datamodel(self.datamodel_registry) Datamodel2._build_datamodel(self.datamodel_registry) Datamodel3._build_datamodel(self.datamodel_registry) Datamodel4._build_datamodel(self.datamodel_registry) self.assertEqual( (Datamodel1, self.env.datamodels["base"]), self.env.datamodels["datamodel1"].__bases__, ) self.assertEqual( ( Datamodel2, self.env.datamodels["datamodel1"], self.env.datamodels["base"], ), self.env.datamodels["datamodel2"].__bases__, ) self.assertEqual( ( Datamodel3, self.env.datamodels["datamodel1"], self.env.datamodels["base"], ), self.env.datamodels["datamodel3"].__bases__, ) self.assertEqual( ( Datamodel4, self.env.datamodels["datamodel2"], self.env.datamodels["datamodel3"], self.env.datamodels["base"], ), self.env.datamodels["datamodel4"].__bases__, ) def test_final_class_schema(self): """Check the MArshmallow schema of the final class""" class Datamodel1(Datamodel): _name = "datamodel1" field_int = fields.Int(load_default=1) class Datamodel2(Datamodel): _name = "datamodel2" _inherit = "datamodel1" field_boolean = fields.Boolean(load_default=True) field_int = fields.Int(load_default=2) class Datamodel3(Datamodel): _name = "datamodel3" _inherit = "datamodel1" field_float = fields.Float(load_default=0.3) class Datamodel4(Datamodel): _name = "datamodel4" _inherit = ["datamodel2", "datamodel3"] Datamodel1._build_datamodel(self.datamodel_registry) Datamodel2._build_datamodel(self.datamodel_registry) Datamodel3._build_datamodel(self.datamodel_registry) Datamodel4._build_datamodel(self.datamodel_registry) Datamodel1 = self.env.datamodels["datamodel1"] Datamodel2 = self.env.datamodels["datamodel2"] Datamodel3 = self.env.datamodels["datamodel3"] Datamodel4 = self.env.datamodels["datamodel4"] self.assertEqual(Datamodel1().dump(), {"field_int": 1}) self.assertDictEqual( Datamodel2().dump(), {"field_boolean": True, "field_int": 2} ) self.assertDictEqual(Datamodel3().dump(), {"field_float": 0.3, "field_int": 1}) self.assertDictEqual( Datamodel4().dump(), {"field_boolean": True, "field_int": 2, "field_float": 0.3}, ) def test_custom_build(self): """Check that we can hook at the end of a Datamodel build""" class Datamodel1(Datamodel): _name = "datamodel1" @classmethod def _complete_datamodel_build(cls): # This method should be called after the Datamodel # is built, and before it is pushed in the registry cls._build_done = True Datamodel1._build_datamodel(self.datamodel_registry) # we inspect that our custom build has been executed self.assertTrue(self.env.datamodels["datamodel1"]._build_done) # pylint: disable=W8110 def test_inherit_attrs(self): """Check attributes inheritance of Datamodels with _inherit""" class Datamodel1(Datamodel): _name = "datamodel1" msg = "ping" def say(self): return "foo" class Datamodel2(Datamodel): _name = "datamodel2" _inherit = "datamodel1" msg = "pong" def say(self): return super(Datamodel2, self).say() + " bar" Datamodel1._build_datamodel(self.datamodel_registry) Datamodel2._build_datamodel(self.datamodel_registry) # we initialize the datamodels, normally we should pass # an instance of WorkContext, but we don't need a real one # for this test datamodel1 = self.env.datamodels["datamodel1"](mock.Mock()) datamodel2 = self.env.datamodels["datamodel2"](mock.Mock()) self.assertEqual("ping", datamodel1.msg) self.assertEqual("pong", datamodel2.msg) self.assertEqual("foo", datamodel1.say()) self.assertEqual("foo bar", datamodel2.say()) def test_duplicate_datamodel(self): """Check that we can't have 2 datamodels with the same name""" class Datamodel1(Datamodel): _name = "datamodel1" class Datamodel2(Datamodel): _name = "datamodel1" Datamodel1._build_datamodel(self.datamodel_registry) msg = "Datamodel.*already exists.*" with self.assertRaisesRegex(TypeError, msg): Datamodel2._build_datamodel(self.datamodel_registry) def test_no_parent(self): """Ensure we can't _inherit a non-existent datamodel""" class Datamodel1(Datamodel): _name = "datamodel1" _inherit = "datamodel1" msg = "Datamodel.*does not exist in registry.*" with self.assertRaisesRegex(TypeError, msg): Datamodel1._build_datamodel(self.datamodel_registry) def test_no_parent2(self): """Ensure we can't _inherit by prototype a non-existent datamodel""" class Datamodel1(Datamodel): _name = "datamodel1" class Datamodel2(Datamodel): _name = "datamodel2" _inherit = ["datamodel1", "datamodel3"] Datamodel1._build_datamodel(self.datamodel_registry) msg = "Datamodel.*inherits from non-existing datamodel.*" with self.assertRaisesRegex(TypeError, msg): Datamodel2._build_datamodel(self.datamodel_registry) def test_add_inheritance(self): """Ensure we can add a new inheritance""" class Datamodel1(Datamodel): _name = "datamodel1" class Datamodel2(Datamodel): _name = "datamodel2" class Datamodel2bis(Datamodel): _name = "datamodel2" _inherit = ["datamodel2", "datamodel1"] Datamodel1._build_datamodel(self.datamodel_registry) Datamodel2._build_datamodel(self.datamodel_registry) Datamodel2bis._build_datamodel(self.datamodel_registry) self.assertEqual( ( Datamodel2bis, Datamodel2, self.env.datamodels["datamodel1"], self.env.datamodels.registry.get("base"), ), self.env.datamodels["datamodel2"].__bases__, ) def test_add_inheritance_final_schema(self): """Ensure that the Marshmallow schema is updated if we add a new inheritance""" class Datamodel1(Datamodel): _name = "datamodel1" field_str1 = fields.String(load_default="str1") class Datamodel2(Datamodel): _name = "datamodel2" field_str2 = fields.String(load_default="str2") class Datamodel2bis(Datamodel): _name = "datamodel2" _inherit = ["datamodel2", "datamodel1"] field_str3 = fields.String(load_default="str3") Datamodel1._build_datamodel(self.datamodel_registry) Datamodel2._build_datamodel(self.datamodel_registry) Datamodel2bis._build_datamodel(self.datamodel_registry) Datamodel2 = self.env.datamodels["datamodel2"] self.assertDictEqual( Datamodel2().dump(), {"field_str1": "str1", "field_str2": "str2", "field_str3": "str3"}, ) def test_recursion(self): class Datamodel1(Datamodel): _name = "datamodel1" field_str = fields.String() Datamodel1._build_datamodel(self.datamodel_registry) for _i in range(0, 1000): self.env.datamodels["datamodel1"](field_str="1234") def test_nested_model(self): """Test nested model serialization/deserialization""" class Parent(Datamodel): _name = "parent" name = fields.String() child = fields.NestedModel("child") class Child(Datamodel): _name = "child" field_str = fields.String() Parent._build_datamodel(self.datamodel_registry) Child._build_datamodel(self.datamodel_registry) Parent = self.env.datamodels["parent"] Child = self.env.datamodels["child"] instance = Parent(name="Parent", child=Child(field_str="My other string")) res = instance.dump() self.assertDictEqual( res, {"child": {"field_str": "My other string"}, "name": "Parent"} ) new_instance = instance.load(res) self.assertEqual(new_instance.name, instance.name) self.assertEqual(new_instance.child.field_str, instance.child.field_str) def test_list_nested_model(self): """Test list model of nested model serialization/deserialization""" class Parent(Datamodel): _name = "parent" name = fields.String() list_child = fields.List(fields.NestedModel("child")) class Child(Datamodel): _name = "child" field_str = fields.String() Parent._build_datamodel(self.datamodel_registry) Child._build_datamodel(self.datamodel_registry) Parent = self.env.datamodels["parent"] Child = self.env.datamodels["child"] childs = [ Child(field_str="My 1st other string"), Child(field_str="My 2nd other string"), ] instance = Parent(name="Parent", list_child=childs) res = instance.dump() self.assertDictEqual( res, { "list_child": [ {"field_str": "My 1st other string"}, {"field_str": "My 2nd other string"}, ], "name": "Parent", }, ) new_instance = instance.load(res) self.assertEqual(new_instance.name, instance.name) self.assertEqual(new_instance.list_child, instance.list_child) def test_many(self): """Test loads of many""" class Item(Datamodel): _name = "item" idx = fields.Integer() Item._build_datamodel(self.datamodel_registry) Item = self.env.datamodels["item"] items = Item.load([{"idx": 1}, {"idx": 2}], many=True) self.assertTrue(len(items), 2) self.assertEqual([i.idx for i in items], [1, 2]) def test_nested_many(self): """Tests loads and dump of model with array of nested model""" class Parent(Datamodel): _name = "parent" items = fields.NestedModel("item", many=True) class Item(Datamodel): _name = "item" idx = fields.Integer() Parent._build_datamodel(self.datamodel_registry) Item._build_datamodel(self.datamodel_registry) Parent = self.env.datamodels["parent"] Item = self.env.datamodels["item"] instance = Parent.load({"items": [{"idx": 1}, {"idx": 2}]}) res = instance.dump() self.assertEqual(res, {"items": [{"idx": 1}, {"idx": 2}]}) new_instance = Parent.load(res) self.assertEqual(len(new_instance.items), 2) self.assertEqual([i.idx for i in new_instance.items], [1, 2]) new_instance.items.append(Item(idx=3)) res = new_instance.dump() self.assertEqual(res, {"items": [{"idx": 1}, {"idx": 2}, {"idx": 3}]}) def test_env(self): """ Tests that the current env is always available on datamodel instances and schema """ class Parent(Datamodel): _name = "parent" items = fields.NestedModel("item", many=True) class Item(Datamodel): _name = "item" idx = fields.Integer() Parent._build_datamodel(self.datamodel_registry) Item._build_datamodel(self.datamodel_registry) Parent = self.env.datamodels["parent"] p = Parent() self.assertEqual(p.env, self.env) schema = Parent.get_schema() self.assertEqual(schema._env, self.env) instance = Parent.load({"items": [{"idx": 1}, {"idx": 2}]}) self.assertEqual(instance.items[0].env, self.env) schema = instance.items[0].get_schema() self.assertEqual(schema._env, self.env) another_env = api.Environment(self.env.registry.cursor(), SUPERUSER_ID, {}) new_p = another_env.datamodels["parent"]() self.assertEqual(new_p.env, another_env) class TestRegistryAccess(TransactionDatamodelCase): def test_registry_access(self): """Check the access to the registry directly on tnv""" base = self.env.datamodels["base"] self.assertIsInstance(base(), MarshmallowModel)
34.925773
16,939
1,265
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA (http://www.camptocamp.com) # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). import logging _logger = logging.getLogger(__name__) def post_init_hook(cr, version): """Preserve log entries from old implementation in shopfloor.""" cr.execute("SELECT 1 FROM pg_class WHERE relname = 'shopfloor_log'") if not cr.fetchone(): # shopfloor_log was already removed return _logger.info("Copy shopfloor.log records to rest.log") cr.execute( """ INSERT INTO rest_log ( request_url, request_method, params, headers, result, error, exception_name, exception_message, state, severity, create_uid, create_date, write_uid, write_date ) SELECT request_url, request_method, params, headers, result, error, exception_name, exception_message, state, severity, create_uid, create_date, write_uid, write_date FROM shopfloor_log; """ ) _logger.info("Delete legacy records in shopfloor_log") cr.execute("""DELETE FROM shopfloor_log""")
23.867925
1,265
766
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA (http://www.camptocamp.com) # Copyright 2021 ACSONE SA/NV (http://www.acsone.eu) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "REST Log", "summary": "Track REST API calls into DB", "version": "15.0.1.0.1", "development_status": "Beta", "website": "https://github.com/OCA/rest-framework", "author": "Camptocamp, ACSONE, Odoo Community Association (OCA)", "maintainers": ["simahawk"], "license": "LGPL-3", "depends": ["base_rest"], "data": [ "data/ir_config_parameter_data.xml", "data/ir_cron_data.xml", "security/groups.xml", "security/ir.model.access.csv", "views/rest_log_views.xml", "views/menu.xml", ], }
33.304348
766
672
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA (http://www.camptocamp.com) # @author Simone Orsi <simahawk@gmail.com> from odoo import exceptions as odoo_exceptions class RESTServiceDispatchException(Exception): rest_json_info = {} def __init__(self, message, log_entry_url): super().__init__(message) self.rest_json_info = {"log_entry_url": log_entry_url} class RESTServiceUserErrorException( RESTServiceDispatchException, odoo_exceptions.UserError ): """User error wrapped exception.""" class RESTServiceValidationErrorException( RESTServiceDispatchException, odoo_exceptions.ValidationError ): """Validation error wrapped exception."""
26.88
672
13,366
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA (http://www.camptocamp.com) # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). # from urllib.parse import urlparse import json import mock from odoo import exceptions from odoo.tools import mute_logger from odoo.addons.base_rest.controllers.main import _PseudoCollection from odoo.addons.base_rest.tests.common import TransactionRestServiceRegistryCase from odoo.addons.component.tests.common import new_rollbacked_env from odoo.addons.rest_log import exceptions as log_exceptions # pylint: disable=W7950 from .common import TestDBLoggingMixin class TestDBLogging(TransactionRestServiceRegistryCase, TestDBLoggingMixin): @classmethod def setUpClass(cls): super().setUpClass() cls._setup_registry(cls) cls.service = cls._get_service(cls) cls.log_model = cls.env["rest.log"].sudo() @classmethod def tearDownClass(cls): # pylint: disable=W8110 cls._teardown_registry(cls) super().tearDownClass() def test_log_enabled_conf_parsing(self): key1 = "coll1.service1.endpoint" key2 = "coll1.service2.endpoint:failed" key3 = "coll2.service1.endpoint:success" self.env["ir.config_parameter"].sudo().set_param( "rest.log.active", ",".join((key1, key2, key3)) ) expected = { # fmt:off "coll1.service1.endpoint": ("success", "failed"), "coll1.service2.endpoint": ("failed", ), "coll2.service1.endpoint": ("success", ), # fmt: on } self.assertEqual(self.env["rest.log"]._get_log_active_conf(), expected) def test_log_enabled(self): self.service._log_calls_in_db = False with self._get_mocked_request(): # no conf no flag self.assertFalse(self.service._db_logging_active("avg_endpoint")) # by conf for collection self.env["ir.config_parameter"].sudo().set_param( "rest.log.active", self.service._collection ) self.assertTrue(self.service._db_logging_active("avg_endpoint")) # by conf for usage self.env["ir.config_parameter"].sudo().set_param( "rest.log.active", self.service._collection + "." + self.service._usage ) self.assertTrue(self.service._db_logging_active("avg_endpoint")) # by conf for usage and endpoint self.env["ir.config_parameter"].sudo().set_param( "rest.log.active", self.service._collection + "." + self.service._usage + ".avg_endpoint", ) self.assertTrue(self.service._db_logging_active("avg_endpoint")) self.assertFalse(self.service._db_logging_active("not_so_avg_endpoint")) # no conf, service class flag self.env["ir.config_parameter"].sudo().set_param("rest.log.active", "") self.service._log_calls_in_db = True self.assertTrue(self.service._db_logging_active("avg_endpoint")) def test_no_log_entry(self): self.service._log_calls_in_db = False log_entry_count = self.log_model.search_count([]) with self._get_mocked_request(): resp = self.service.dispatch("get", 100) self.assertNotIn("log_entry_url", resp) self.assertFalse(self.log_model.search_count([]) > log_entry_count) def test_log_entry(self): log_entry_count = self.log_model.search_count([]) with self._get_mocked_request(): resp = self.service.dispatch("get", 100) self.assertIn("log_entry_url", resp) self.assertTrue(self.log_model.search_count([]) > log_entry_count) def test_log_entry_values_success(self): params = {"some": "value"} kw = {"result": {"data": "worked!"}} # test full data request only once, other tests will skip this part httprequest = mock.Mock( url="https://my.odoo.test/service/endpoint", method="POST" ) extra_headers = {"KEEP-ME": "FOO"} with self._get_mocked_request( httprequest=httprequest, extra_headers=extra_headers ) as mocked_request: entry = self.service._log_call_in_db( self.env, mocked_request, "avg_method", params=params, **kw ) expected = { "collection": self.service._collection, "request_url": httprequest.url, "request_method": httprequest.method, "state": "success", "error": False, "exception_name": False, "severity": False, } self.assertRecordValues(entry, [expected]) expected_json = { "result": {"data": "worked!"}, "params": dict(params), "headers": { "Cookie": "<redacted>", "Api-Key": "<redacted>", "KEEP-ME": "FOO", }, } for k, v in expected_json.items(): self.assertEqual(json.loads(entry[k]), v) def test_log_entry_values_failed(self): params = {"some": "value"} # no result, will fail kw = {"result": {}} with self._get_mocked_request() as mocked_request: entry = self.service._log_call_in_db( self.env, mocked_request, "avg_method", params=params, **kw ) expected = { "collection": self.service._collection, "state": "failed", "result": "{}", "error": False, "exception_name": False, "severity": False, } self.assertRecordValues(entry, [expected]) def _test_log_entry_values_failed_with_exception_default(self, severity=None): params = {"some": "value"} fake_tb = """ [...] File "/somewhere/in/your/custom/code/file.py", line 503, in write [...] ValueError: Ops, something went wrong """ orig_exception = ValueError("Ops, something went wrong") kw = {"result": {}, "traceback": fake_tb, "orig_exception": orig_exception} with self._get_mocked_request() as mocked_request: entry = self.service._log_call_in_db( self.env, mocked_request, "avg_method", params=params, **kw ) expected = { "collection": self.service._collection, "state": "failed", "result": "{}", "error": fake_tb, "exception_name": "ValueError", "exception_message": "Ops, something went wrong", "severity": severity or "severe", } self.assertRecordValues(entry, [expected]) def test_log_entry_values_failed_with_exception_default(self): self._test_log_entry_values_failed_with_exception_default() def test_log_entry_values_failed_with_exception_functional(self): params = {"some": "value"} fake_tb = """ [...] File "/somewhere/in/your/custom/code/file.py", line 503, in write [...] UserError: You are doing something wrong Dave! """ orig_exception = exceptions.UserError("You are doing something wrong Dave!") kw = {"result": {}, "traceback": fake_tb, "orig_exception": orig_exception} with self._get_mocked_request() as mocked_request: entry = self.service._log_call_in_db( self.env, mocked_request, "avg_method", params=params, **kw ) expected = { "collection": self.service._collection, "state": "failed", "result": "{}", "error": fake_tb, "exception_name": "odoo.exceptions.UserError", "exception_message": "You are doing something wrong Dave!", "severity": "functional", } self.assertRecordValues(entry, [expected]) # test that we can still change severity as we like entry.severity = "severe" self.assertEqual(entry.severity, "severe") def test_log_entry_severity_mapping_param(self): # test override of mapping via config param mapping = self.log_model._get_exception_severity_mapping() self.assertEqual(mapping, self.log_model.EXCEPTION_SEVERITY_MAPPING) self.assertEqual(mapping["ValueError"], "severe") self.assertEqual(mapping["odoo.exceptions.UserError"], "functional") value = "ValueError: warning, odoo.exceptions.UserError: severe" self.env["ir.config_parameter"].sudo().create( {"key": "rest.log.severity.exception.mapping", "value": value} ) mapping = self.log_model._get_exception_severity_mapping() self.assertEqual(mapping["ValueError"], "warning") self.assertEqual(mapping["odoo.exceptions.UserError"], "severe") self._test_log_entry_values_failed_with_exception_default("warning") @mute_logger("odoo.addons.rest_log.models.rest_log") def test_log_entry_severity_mapping_param_bad_values(self): # bad values are discarded value = """ ValueError: warning, odoo.exceptions.UserError::badvalue, VeryBadValue|error """ self.env["ir.config_parameter"].sudo().create( {"key": "rest.log.severity.exception.mapping", "value": value} ) mapping = self.log_model._get_exception_severity_mapping() expected = self.log_model.EXCEPTION_SEVERITY_MAPPING.copy() expected["ValueError"] = "warning" self.assertEqual(mapping, expected) class TestDBLoggingExceptionBase( TransactionRestServiceRegistryCase, TestDBLoggingMixin ): @classmethod def setUpClass(cls): super().setUpClass() cls._setup_registry(cls) @classmethod def tearDownClass(cls): # pylint: disable=W8110 cls._teardown_registry(cls) super().tearDownClass() def _test_exception(self, test_type, wrapping_exc, exc_name, severity): log_model = self.env["rest.log"].sudo() initial_entries = log_model.search([]) entry_url_from_exc = None # Context: we are running in a transaction case which uses savepoints. # The log machinery is going to rollback the transation when catching errors. # Hence we need a completely separated env for the service. with new_rollbacked_env() as new_env: # Init fake collection w/ new env collection = _PseudoCollection(self._collection_name, new_env) service = self._get_service(self, collection=collection) with self._get_mocked_request(env=new_env): try: service.dispatch("fail", test_type) except Exception as err: # Not using `assertRaises` to inspect the exception directly self.assertTrue(isinstance(err, wrapping_exc)) self.assertEqual( service._get_exception_message(err), "Failed as you wanted!" ) entry_url_from_exc = err.rest_json_info["log_entry_url"] with new_rollbacked_env() as new_env: log_model = new_env["rest.log"].sudo() entry = log_model.search([]) - initial_entries expected = { "collection": service._collection, "state": "failed", "result": "null", "exception_name": exc_name, "exception_message": "Failed as you wanted!", "severity": severity, } self.assertRecordValues(entry, [expected]) self.assertEqual(entry_url_from_exc, service._get_log_entry_url(entry)) class TestDBLoggingExceptionUserError(TestDBLoggingExceptionBase): @staticmethod def _get_test_controller(class_or_instance, root_path=None): # Override to avoid registering twice the same controller route. return super()._get_test_controller( class_or_instance, root_path="/test_log_exception_user/" ) def test_log_exception_user(self): self._test_exception( "user", log_exceptions.RESTServiceUserErrorException, "odoo.exceptions.UserError", "functional", ) class TestDBLoggingExceptionValidationError(TestDBLoggingExceptionBase): @staticmethod def _get_test_controller(class_or_instance, root_path=None): return super()._get_test_controller( class_or_instance, root_path="/test_log_exception_validation/" ) def test_log_exception_validation(self): self._test_exception( "validation", log_exceptions.RESTServiceValidationErrorException, "odoo.exceptions.ValidationError", "functional", ) class TestDBLoggingExceptionValueError(TestDBLoggingExceptionBase): @staticmethod def _get_test_controller(class_or_instance, root_path=None): return super()._get_test_controller( class_or_instance, root_path="/test_log_exception_value/" ) def test_log_exception_value(self): self._test_exception( "value", log_exceptions.RESTServiceDispatchException, "ValueError", "severe" )
40.75
13,366
2,540
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA (http://www.camptocamp.com) # @author Simone Orsi <simahawk@gmail.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). import contextlib from odoo import exceptions from odoo.addons.base_rest import restapi from odoo.addons.component.core import Component from odoo.addons.website.tools import MockRequest class TestDBLoggingMixin(object): @staticmethod def _get_service(class_or_instance, collection=None): # pylint: disable=R7980 class LoggedService(Component): _inherit = "base.rest.service" _name = "test.log.service" _usage = "logmycalls" _collection = class_or_instance._collection_name _description = "Test log my calls" _log_calls_in_db = True @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=restapi.CerberusValidator("_get_out_schema"), auth="public", ) def get(self, _id): """Get some information""" return {"name": "Mr Logger"} def _get_out_schema(self): return {"name": {"type": "string", "required": True}} @restapi.method([(["/fail/<string:how>"], "GET")], auth="public") def fail(self, how): """Test a failure""" exc = { "value": ValueError, "validation": exceptions.ValidationError, "user": exceptions.UserError, } raise exc[how]("Failed as you wanted!") class_or_instance.comp_registry.load_components("rest_log") # class_or_instance._build_services(class_or_instance, LoggedService) # TODO: WTH _build_services does not load the component? LoggedService._build_component(class_or_instance.comp_registry) return class_or_instance._get_service_component( class_or_instance, "logmycalls", collection=collection ) @contextlib.contextmanager def _get_mocked_request(self, env=None, httprequest=None, extra_headers=None): with MockRequest(env or self.env) as mocked_request: mocked_request.httprequest = httprequest or mocked_request.httprequest headers = {"Cookie": "IaMaCookie!", "Api-Key": "I_MUST_STAY_SECRET"} headers.update(extra_headers or {}) mocked_request.httprequest.headers = headers yield mocked_request
40.31746
2,540
7,220
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA (http://www.camptocamp.com) # @author Guewen Baconnier <guewen.baconnier@camptocamp.com> # @author Simone Orsi <simahawk@gmail.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). import logging from datetime import datetime, timedelta from odoo import api, fields, models, tools _logger = logging.getLogger(__name__) class RESTLog(models.Model): _name = "rest.log" _description = "REST API Logging" _order = "id desc" DEFAULT_RETENTION = 30 # days EXCEPTION_SEVERITY_MAPPING = { "odoo.exceptions.UserError": "functional", "odoo.exceptions.ValidationError": "functional", # something broken somewhere "ValueError": "severe", "AttributeError": "severe", "UnboundLocalError": "severe", } collection = fields.Char(index=True) collection_id = fields.Integer(index=True, string="Collection ID") request_url = fields.Char(readonly=True, string="Request URL") request_method = fields.Char(readonly=True) params = fields.Text(readonly=True) # TODO: make these fields serialized and use a computed field for displaying headers = fields.Text(readonly=True) result = fields.Text(readonly=True) error = fields.Text(readonly=True) exception_name = fields.Char(readonly=True, string="Exception") exception_message = fields.Text(readonly=True) state = fields.Selection( selection=[("success", "Success"), ("failed", "Failed")], readonly=True ) severity = fields.Selection( selection=[ ("functional", "Functional"), ("warning", "Warning"), ("severe", "Severe"), ], compute="_compute_severity", store=True, # Grant specific override services' dispatch_exception override # or via UI: user can classify errors as preferred on demand # (maybe using mass_edit) readonly=False, ) @api.depends("state", "exception_name", "error") def _compute_severity(self): for rec in self: rec.severity = rec.severity or rec._get_severity() def _get_severity(self): if not self.exception_name: return False mapping = self._get_exception_severity_mapping() return mapping.get(self.exception_name, "warning") def _get_exception_severity_mapping_param(self): param = ( self.env["ir.config_parameter"] .sudo() .get_param("rest.log.severity.exception.mapping") ) return param.strip() if param else "" @tools.ormcache("self._get_exception_severity_mapping_param()") def _get_exception_severity_mapping(self): mapping = self.EXCEPTION_SEVERITY_MAPPING.copy() param = self._get_exception_severity_mapping_param() if not param: return mapping # param should be in the form # `[module.dotted.path.]ExceptionName:severity,ExceptionName:severity` for rule in param.split(","): if not rule.strip(): continue exc_name = severity = None try: exc_name, severity = [x.strip() for x in rule.split(":")] if not exc_name or not severity: raise ValueError except ValueError: _logger.info( "Could not convert System Parameter" " 'rest.log.severity.exception.mapping' to mapping." " The following rule will be ignored: %s", rule, ) if exc_name and severity: mapping[exc_name] = severity return mapping def _logs_retention_days(self): retention = self.DEFAULT_RETENTION param = ( self.env["ir.config_parameter"].sudo().get_param("rest.log.retention.days") ) if param: try: retention = int(param) except ValueError: _logger.exception( "Could not convert System Parameter" " 'rest.log.retention.days' to integer," " reverting to the" " default configuration." ) return retention def logging_active(self): retention = self._logs_retention_days() return retention > 0 def autovacuum(self): """Delete logs which have exceeded their retention duration Called from a cron. """ deadline = datetime.now() - timedelta(days=self._logs_retention_days()) logs = self.search([("create_date", "<=", deadline)]) if logs: logs.unlink() return True def _get_log_active_param(self): param = self.env["ir.config_parameter"].sudo().get_param("rest.log.active") return param.strip() if param else "" @tools.ormcache("self._get_log_active_param()") def _get_log_active_conf(self): """Compute log active configuration. Possible configuration contains a CSV like this: `collection_name` -> enable for all endpoints of the collection `collection_name.usage` -> enable for specific endpoints `collection_name.usage.endpoint` -> enable for specific endpoints `collection_name*:state` -> enable only for specific state (success, failed) By default matching keys are enabled for all states. :return: mapping by matching key / enabled states """ param = self._get_log_active_param() conf = {} lines = [x.strip() for x in param.split(",") if x.strip()] for line in lines: bits = [x.strip() for x in line.split(":") if x.strip()] if len(bits) > 1: match_key = bits[0] # fmt: off states = (bits[1], ) # fmt: on else: match_key = line states = ("success", "failed") conf[match_key] = states return conf @api.model def _get_matching_active_conf(self, collection, usage, method_name): """Retrieve conf matching current service and method.""" conf = self._get_log_active_conf() candidates = ( collection + "." + usage + "." + method_name, collection + "." + usage, collection, ) for candidate in candidates: if conf.get(candidate): return conf.get(candidate) def action_view_collection(self): """Open collection if we have a real record. NOTE: use an action instead of a `Reference` field with computed method because it would force use to have glue modules to provide a selection for every model we want to support. """ # TODO: on the next round, compute the collection name # to be used for the button label. # No ID or no real model if self.collection not in self.env or not self.collection_id: return action = self.env[self.collection].get_formview_action() action["res_id"] = self.collection_id return action
36.836735
7,220
6,610
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA (http://www.camptocamp.com) # @author Guewen Baconnier <guewen.baconnier@camptocamp.com> # @author Simone Orsi <simahawk@gmail.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). import json import traceback from werkzeug.urls import url_encode, url_join from odoo import exceptions, registry from odoo.http import request from odoo.addons.base_rest.http import JSONEncoder from odoo.addons.component.core import AbstractComponent from ..exceptions import ( RESTServiceDispatchException, RESTServiceUserErrorException, RESTServiceValidationErrorException, ) def json_dump(data): """Encode data to JSON as we like.""" return json.dumps(data, cls=JSONEncoder, indent=4, sort_keys=True) class BaseRESTService(AbstractComponent): _inherit = "base.rest.service" # can be overridden to enable logging of requests to DB _log_calls_in_db = False def dispatch(self, method_name, *args, params=None): if not self._db_logging_active(method_name): return super().dispatch(method_name, *args, params=params) return self._dispatch_with_db_logging(method_name, *args, params=params) def _dispatch_with_db_logging(self, method_name, *args, params=None): # TODO: consider refactoring thi using a savepoint as described here # https://github.com/OCA/rest-framework/pull/106#pullrequestreview-582099258 try: result = super().dispatch(method_name, *args, params=params) except exceptions.ValidationError as orig_exception: self._dispatch_exception( method_name, RESTServiceValidationErrorException, orig_exception, *args, params=params, ) except exceptions.UserError as orig_exception: self._dispatch_exception( method_name, RESTServiceUserErrorException, orig_exception, *args, params=params, ) except Exception as orig_exception: self._dispatch_exception( method_name, RESTServiceDispatchException, orig_exception, *args, params=params, ) log_entry = self._log_call_in_db( self.env, request, method_name, *args, params=params, result=result ) if log_entry and isinstance(result, dict): log_entry_url = self._get_log_entry_url(log_entry) result["log_entry_url"] = log_entry_url return result def _dispatch_exception( self, method_name, exception_klass, orig_exception, *args, params=None ): tb = traceback.format_exc() # TODO: how to test this? Cannot rollback nor use another cursor self.env.cr.rollback() with registry(self.env.cr.dbname).cursor() as cr: env = self.env(cr=cr) log_entry = self._log_call_in_db( env, request, method_name, *args, params=params, traceback=tb, orig_exception=orig_exception, ) log_entry_url = self._get_log_entry_url(log_entry) # UserError and alike have `name` attribute to store the msg exc_msg = self._get_exception_message(orig_exception) raise exception_klass(exc_msg, log_entry_url) from orig_exception def _get_exception_message(self, exception): return exception.args and exception.args[0] or str(exception) def _get_log_entry_url(self, entry): base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url") url_params = { "action": self.env.ref("rest_log.action_rest_log").id, "view_type": "form", "model": entry._name, "id": entry.id, } url = "/web?#%s" % url_encode(url_params) return url_join(base_url, url) @property def _log_call_header_strip(self): return ("Cookie", "Api-Key") def _log_call_in_db_values(self, _request, *args, params=None, **kw): httprequest = _request.httprequest headers = dict(httprequest.headers) for header_key in self._log_call_header_strip: if header_key in headers: headers[header_key] = "<redacted>" if args: params = dict(params or {}, args=args) params = self._log_call_sanitize_params(params) result = kw.get("result") error = kw.get("traceback") orig_exception = kw.get("orig_exception") exception_name = None exception_message = None if orig_exception: exception_name = orig_exception.__class__.__name__ if hasattr(orig_exception, "__module__"): exception_name = orig_exception.__module__ + "." + exception_name exception_message = self._get_exception_message(orig_exception) collection = self.work.collection return { "collection": collection._name, "collection_id": collection.id, "request_url": httprequest.url, "request_method": httprequest.method, "params": json_dump(params), "headers": json_dump(headers), "result": json_dump(result), "error": error, "exception_name": exception_name, "exception_message": exception_message, "state": "success" if result else "failed", } def _log_call_in_db(self, env, _request, method_name, *args, params=None, **kw): values = self._log_call_in_db_values(_request, *args, params=params, **kw) enabled_states = self._get_matching_active_conf(method_name) if not values or enabled_states and values["state"] not in enabled_states: return return env["rest.log"].sudo().create(values) def _log_call_sanitize_params(self, params): if "password" in params: params["password"] = "<redacted>" return params def _db_logging_active(self, method_name): enabled = self._log_calls_in_db if not enabled: enabled = bool(self._get_matching_active_conf(method_name)) return request and enabled and self.env["rest.log"].logging_active() def _get_matching_active_conf(self, method_name): return self.env["rest.log"]._get_matching_active_conf( self._collection, self._usage, method_name )
38.208092
6,610
1,473
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import graphene from odoo import fields def odoo_attr_resolver(attname, default_value, root, info, **args): """An attr resolver that is specialized for Odoo recordsets. It converts False to None, except for Odoo Boolean fields. This is necessary because Odoo null values are often represented as False, and graphene would convert a String field with value False to "false". It converts datetimes to the user timezone. It also raises an error if the attribute is not present, ignoring any default value, so as to return if the schema declares a field that is not present in the underlying Odoo model. """ value = getattr(root, attname) field = root._fields.get(attname) if value is False: if not isinstance(field, fields.Boolean): return None elif isinstance(field, fields.Datetime): return fields.Datetime.context_timestamp(root, value) return value class OdooObjectType(graphene.ObjectType): """A graphene ObjectType with an Odoo aware default resolver.""" @classmethod def __init_subclass_with_meta__(cls, default_resolver=None, **options): if default_resolver is None: default_resolver = odoo_attr_resolver return super(OdooObjectType, cls).__init_subclass_with_meta__( default_resolver=default_resolver, **options )
34.255814
1,473
602
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Graphql Base", "summary": """ Base GraphQL/GraphiQL controller""", "version": "15.0.1.0.1", "license": "LGPL-3", "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/rest-framework", "depends": ["base"], "data": ["views/graphiql.xml"], "external_dependencies": {"python": ["graphene", "graphql_server"]}, "development_status": "Production/Stable", "maintainers": ["sbidoul"], "installable": True, }
33.444444
602
3,785
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import re from functools import partial from graphql_server import ( HttpQueryError, encode_execution_results, format_error_default, json_encode, load_json_body, run_http_query, ) from odoo import http class GraphQLControllerMixin(object): @staticmethod def patch_for_json(path_re): # this is to avoid Odoo, which assumes json always means json+rpc, # complaining about "function declared as capable of handling request # of type 'http' but called with a request of type 'json'" path_re = re.compile(path_re) orig_get_request = http.Root.get_request def get_request(self, httprequest): if path_re.match(httprequest.path): return http.HttpRequest(httprequest) return orig_get_request(self, httprequest) http.Root.get_request = get_request def _parse_body(self): req = http.request.httprequest # We use mimetype here since we don't need the other # information provided by content_type content_type = req.mimetype if content_type == "application/graphql": return {"query": req.data.decode("utf8")} elif content_type == "application/json": return load_json_body(req.data.decode("utf8")) elif content_type in ( "application/x-www-form-urlencoded", "multipart/form-data", ): return http.request.params return {} def _process_request(self, schema, data): try: request = http.request.httprequest execution_results, all_params = run_http_query( schema, request.method.lower(), data, query_data=request.args, batch_enabled=False, catch=False, context_value={"env": http.request.env}, ) result, status_code = encode_execution_results( execution_results, is_batch=isinstance(data, list), format_error=format_error_default, encode=partial(json_encode, pretty=False), ) headers = dict() headers["Content-Type"] = "application/json" response = http.request.make_response(result, headers=headers) response.status_code = status_code if any(er.errors for er in execution_results): env = http.request.env env.cr.rollback() env.clear() return response except HttpQueryError as e: result = json_encode({"errors": [{"message": str(e)}]}) headers = dict(e.headers) headers["Content-Type"] = "application/json" response = http.request.make_response(result, headers=headers) response.status_code = e.status_code env = http.request.env env.cr.rollback() env.clear() return response def _handle_graphql_request(self, schema): data = self._parse_body() return self._process_request(schema, data) def _handle_graphiql_request(self, schema): req = http.request.httprequest if req.method == "GET" and req.accept_mimetypes.accept_html: return http.request.render("graphql_base.graphiql", {}) # this way of passing a GraphQL query over http is not spec compliant # (https://graphql.org/learn/serving-over-http/), but we use # this only for our GraphiQL UI, and it works with Odoo's way # of passing the csrf token return self._process_request(schema, http.request.params)
37.475248
3,785
892
py
PYTHON
15.0
# Copyright 2015-2016 Tecnativa - Jairo Llopis <jairo.llopis@tecnativa.com> # Copyright 2019 Tecnativa - Cristina Martin R. # Copyright 2022 Tecnativa - Guillermo Gallego <guillermo.gallego@tecnativa.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { "name": "Big Buttons Snippet", "summary": "A snippet that adds two big buttons", "version": "15.0.1.0.0", "category": "Website", "website": "https://github.com/OCA/website", "author": "Grupo ESOC Ingeniería de Servicios, S.L.U., " "Tecnativa, " "Odoo Community Association (OCA)", "license": "LGPL-3", "application": False, "installable": True, "depends": ["website"], "data": ["templates/snippets.xml"], "assets": { "web.assets_frontend": [ "/website_snippet_big_button/static/src/scss/website_snippet_big_button.scss" ] }, }
37.125
891
677
py
PYTHON
15.0
# Copyright 2022 Studio73 - Ioan Galan <ioan@studio73.es> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Website Whatsapp", "summary": "Whatsapp integration", "category": "Website", "version": "15.0.1.0.1", "website": "https://github.com/OCA/website", "author": "Studio73, Odoo Community Association (OCA)", "maintainers": ["ioans73"], "license": "AGPL-3", "depends": ["website"], "data": [ "templates/website.xml", "views/res_config_settings.xml", ], "assets": { "web.assets_frontend": ["/website_whatsapp/static/src/scss/website.scss"] }, "installable": True, }
32.238095
677
565
py
PYTHON
15.0
# Copyright 2022 Studio73 - Ioan Galan <ioan@studio73.es> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class Website(models.Model): _inherit = "website" whatsapp_number = fields.Char(string="WhatsApp number") whatsapp_text = fields.Char( "Default text for Whatsapp", help="Default text to send as message", ) whatsapp_track_url = fields.Boolean( "Track URL", help="Indicate in the user's message the URL of the page from which it " "was sent", )
29.736842
565
1,130
py
PYTHON
15.0
# Copyright 2022 Studio73 - Ioan Galan <ioan@studio73.es> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" @api.depends("website_id.whatsapp_number") def _compute_whatsapp_enabled(self): for record in self: record.update({"whatsapp_enabled": bool(record.whatsapp_number)}) def _inverse_whatsapp_enabled(self): for record in self: if not record.whatsapp_enabled: record.website_id.update({"whatsapp_number": False}) whatsapp_number = fields.Char( related="website_id.whatsapp_number", readonly=False, ) whatsapp_text = fields.Char( related="website_id.whatsapp_text", readonly=False, ) whatsapp_track_url = fields.Boolean( related="website_id.whatsapp_track_url", readonly=False, ) whatsapp_enabled = fields.Boolean( string="Use Whatsapp", compute="_compute_whatsapp_enabled", inverse="_inverse_whatsapp_enabled", )
31.388889
1,130
853
py
PYTHON
15.0
# Copyright 2015-2017 Tecnativa - Jairo Llopis <jairo.llopis@tecnativa.com> # Copyright 2019 Tecnativa - Cristina Martin R. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { "name": "Marginless Gallery Snippet", "summary": "Add a snippet to have a marginless image gallery", "version": "15.0.1.0.0", "category": "Website", "license": "LGPL-3", "website": "https://github.com/OCA/website", "author": "Grupo ESOC Ingeniería de Servicios, " "Tecnativa, " "Odoo Community Association (OCA)", "application": False, "installable": True, "images": ["images/marginless_gallery.png"], "depends": ["website"], "data": ["views/snippets.xml"], "assets": { "web.assets_tests": [ "/website_snippet_marginless_gallery/static/src/tests/tours/*.js" ] }, }
35.5
852
482
py
PYTHON
15.0
# Copyright 2015-2017 Tecnativa - Jairo Llopis <jairo.llopis@tecnativa.com> # Copyright 2019 Tecnativa - Cristina Martin R. # Copyright 2021 Tecnativa - Alexandre D. Díaz # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). import odoo.tests from odoo.tests import tagged @tagged("post_install", "-at_install") class TestUi(odoo.tests.HttpCase): def test_admin_tour_marginless_gallery(self): self.start_tour("/", "marginless_gallery", login="admin")
37
481
666
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Jairo Llopis # Copyright 2017 Tecnativa - David Vidal # Copyright 2019 Tecnativa - Cristina Martin R. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Quick answer for website contact form", "summary": "Add an automatic answer for contacts asking for info", "category": "Website", "version": "15.0.1.0.1", "website": "https://github.com/OCA/website", "depends": ["website_crm", "base_automation"], "data": ["data/base_automation_data.xml"], "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, }
39.176471
666
918
py
PYTHON
15.0
# Copyright 2023 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Website Snippet OpenStreetMap", "category": "Website", "version": "15.0.1.0.0", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/website", "depends": [ "base_geolocalize", "website", ], "data": [ "views/snippets/s_openstreetmap.xml", "views/snippets/snippets.xml", ], "demo": [ "demo/res_partner_demo.xml", ], "assets": { "website.assets_wysiwyg": [ ("include", "web._assets_helpers"), "website_snippet_openstreetmap/static/src/snippets/s_openstreetmap/options.js", ], "web.assets_frontend": [ "website_snippet_openstreetmap/static/src/js/utils.js", ], }, }
30.6
918
897
py
PYTHON
15.0
# Copyright (C) 2020 Alexandre Díaz - Tecnativa S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import SUPERUSER_ID, api from odoo.tools import config def post_init_hook(cr, registry): # This is here to not broke the tests. The idea: # - XML changes in website are made using 'customize_show=True' # - When Odoo is running in testing mode, we disable our changes # - When run our test, we enable the changes and test it. (see test file) # # For the user it has no impact (only more customizable options in the website) # For CI/CD avoids problems testing modules that removes/positioning elements # that other modules uses in their tests. if config["test_enable"] or config["test_file"]: env = api.Environment(cr, SUPERUSER_ID, {}) env.ref("website_odoo_debranding.layout_footer_copyright").active = False
49.777778
896
500
py
PYTHON
15.0
# Copyright 2016 Tecnativa, S.L. - Vicent Cubells # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { "name": "Remove Odoo Branding from Website", "version": "15.0.1.0.1", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/website", "license": "LGPL-3", "category": "Website", "depends": ["website"], "data": ["templates/disable_odoo.xml"], "installable": True, "post_init_hook": "post_init_hook", }
35.714286
500
1,166
py
PYTHON
15.0
# Copyright 2016 Sergio Teruel <sergio.teruel@tecnativa.com> # Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Website Snippet Country Code Dropdown", "summary": "Allow to select country in a dropdown", "version": "15.0.1.0.0", "category": "Website", "website": "https://github.com/OCA/website", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "LGPL-3", "application": False, "installable": True, "depends": ["website"], "data": ["views/snippets.xml"], "demo": ["demo/pages.xml"], "assets": { "web.assets_tests": [ "/website_snippet_country_dropdown/static/src/js/" "web_tour_country_dropdown.js" ], "web.assets_frontend": [ "/website_snippet_country_dropdown/static/src/css/style.scss", "/website_snippet_country_dropdown/static/src/js/" "website_snippet_country_dropdown.js", ], "web.assets_qweb": [ "/website_snippet_country_dropdown/static/src/xml/country_dropdown.xml" ], }, }
36.4375
1,166
345
py
PYTHON
15.0
# Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import odoo.tests class TestUi(odoo.tests.HttpCase): def test_01_demo_country_dropdown_tour(self): self.start_tour( "/", "website_snippet_country_dropdown_tour_demo_page", login="admin" )
34.5
345
561
py
PYTHON
15.0
# Copyright 2022 Tecnativa David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Website Forum Subscription", "summary": "Adds a button to allow subscription from the website", "version": "15.0.1.0.0", "category": "Website", "website": "https://github.com/OCA/website", "author": ("Tecnativa, " "Odoo Community Association (OCA)"), "license": "AGPL-3", "application": False, "installable": True, "depends": ["website_forum"], "data": ["templates/website_forum_templates.xml"], }
37.4
561
554
py
PYTHON
15.0
# Copyright 2015 Antonio Espinosa <antonioea@antiun.com> # Copyright 2017 Jairo Llopis <jairo.llopis@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Website Legal Page", "category": "Website", "version": "15.0.2.0.0", "depends": ["website"], "data": [ "views/website_legal_main_page.xml", ], "author": "Tecnativa, " "LasLabs, " "Nicolas JEUDY, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/website", "license": "AGPL-3", }
29.157895
554
397
py
PYTHON
15.0
# Copyright 2017 LasLabs Inc. # Copyright 2020 Tecnativa - Alexandre Díaz # License APL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import HttpCase class TestController(HttpCase): def test_page(self): """It should return a 200 for legal page.""" response = self.url_open("/legal", timeout=20) self.assertEqual(response.status_code, 200)
33
396
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
1,553
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-website", description="Meta package for oca-website Odoo addons", version=version, install_requires=[ 'odoo-addon-website_analytics_matomo>=15.0dev,<15.1dev', 'odoo-addon-website_breadcrumb>=15.0dev,<15.1dev', 'odoo-addon-website_cookiebot>=15.0dev,<15.1dev', 'odoo-addon-website_cookiefirst>=15.0dev,<15.1dev', 'odoo-addon-website_crm_privacy_policy>=15.0dev,<15.1dev', 'odoo-addon-website_crm_quick_answer>=15.0dev,<15.1dev', 'odoo-addon-website_form_require_legal>=15.0dev,<15.1dev', 'odoo-addon-website_forum_subscription>=15.0dev,<15.1dev', 'odoo-addon-website_google_tag_manager>=15.0dev,<15.1dev', 'odoo-addon-website_legal_page>=15.0dev,<15.1dev', 'odoo-addon-website_odoo_debranding>=15.0dev,<15.1dev', 'odoo-addon-website_plausible>=15.0dev,<15.1dev', 'odoo-addon-website_snippet_big_button>=15.0dev,<15.1dev', 'odoo-addon-website_snippet_country_dropdown>=15.0dev,<15.1dev', 'odoo-addon-website_snippet_dynamic_link>=15.0dev,<15.1dev', 'odoo-addon-website_snippet_marginless_gallery>=15.0dev,<15.1dev', 'odoo-addon-website_snippet_openstreetmap>=15.0dev,<15.1dev', 'odoo-addon-website_whatsapp>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
44.371429
1,553
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100