Skip to content

Commit

Permalink
Merge PR #394 into 16.0
Browse files Browse the repository at this point in the history
Signed-off-by lmignon
  • Loading branch information
OCA-git-bot committed Nov 13, 2023
2 parents fecc1ef + 9c64bf4 commit 59d8d0a
Show file tree
Hide file tree
Showing 67 changed files with 200 additions and 204 deletions.
5 changes: 4 additions & 1 deletion .copier-answers.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Do NOT update manually; changes here will be overwritten by Copier
_commit: v1.17.2
_commit: v1.18
_src_path: git+https://github.com/oca/oca-addons-repo-template
additional_ruff_rules: []
ci: GitHub
generate_requirements_txt: true
github_check_license: true
Expand All @@ -20,4 +21,6 @@ repo_description: This repository has nice modules to interact with Odoo using J
repo_name: Rest Frameworks
repo_slug: rest-framework
repo_website: https://github.com/OCA/rest-framework
use_pyproject_toml: false
use_ruff: true

12 changes: 0 additions & 12 deletions .flake8

This file was deleted.

1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ __pycache__/
*.py[cod]
/.venv
/.pytest_cache
/.ruff_cache

# C extensions
*.so
Expand Down
13 changes: 0 additions & 13 deletions .isort.cfg

This file was deleted.

42 changes: 8 additions & 34 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ exclude: |
^docs/_templates/.*\.html$|
# Don't bother non-technical authors with formatting issues in docs
readme/.*\.(rst|md)$|
# Ignore build and dist directories in addons
/build/|/dist/|
# You don't usually want a bot to modify your legal texts
(LICENSE.*|COPYING.*)
default_language_version:
Expand All @@ -39,7 +41,7 @@ repos:
language: fail
files: '[a-zA-Z0-9_]*/i18n/en\.po$'
- repo: https://github.com/oca/maintainer-tools
rev: 969238e47c07d0c40573acff81d170f63245d738
rev: 568cacd1d6eef453063a524a5ce63dcd49c7259b
hooks:
# update the NOT INSTALLABLE ADDONS section above
- id: oca-update-pre-commit-excluded-addons
Expand All @@ -57,21 +59,6 @@ repos:
hooks:
- id: oca-checks-odoo-module
- id: oca-checks-po
- repo: https://github.com/myint/autoflake
rev: v1.6.1
hooks:
- id: autoflake
args:
- --expand-star-imports
- --ignore-init-module-imports
- --in-place
- --remove-all-unused-imports
- --remove-duplicate-keys
- --remove-unused-variables
- repo: https://github.com/psf/black
rev: 22.8.0
hooks:
- id: black
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.7.1
hooks:
Expand Down Expand Up @@ -113,19 +100,6 @@ repos:
- id: check-xml
- id: mixed-line-ending
args: ["--fix=lf"]
- repo: https://github.com/asottile/pyupgrade
rev: v2.38.2
hooks:
- id: pyupgrade
args: ["--keep-percent-format"]
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
name: isort except __init__.py
args:
- --settings=.
exclude: /__init__\.py$
- repo: https://github.com/acsone/setuptools-odoo
rev: 3.1.8
hooks:
Expand All @@ -136,12 +110,12 @@ repos:
- requirements.txt
- --header
- "# generated from manifests external_dependencies"
- repo: https://github.com/PyCQA/flake8
rev: 3.9.2
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.3
hooks:
- id: flake8
name: flake8
additional_dependencies: ["flake8-bugbear==21.9.2"]
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- id: ruff-format
- repo: https://github.com/OCA/pylint-odoo
rev: v8.0.19
hooks:
Expand Down
29 changes: 29 additions & 0 deletions .ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

target-version = "py310"
fix = true

[lint]
extend-select = [
"B",
"C90",
"I", # isort
"UP", # pyupgrade
]
exclude = ["setup/*"]

[format]
exclude = ["setup/*"]

[per-file-ignores]
"__init__.py" = ["F401", "I001"] # ignore unused and unsorted imports in __init__.py
"__manifest__.py" = ["B018"] # useless expression

[isort]
section-order = ["future", "standard-library", "third-party", "odoo", "odoo-addons", "first-party", "local-folder"]

[isort.sections]
"odoo" = ["odoo"]
"odoo-addons" = ["odoo.addons"]

[mccabe]
max-complexity = 16
9 changes: 2 additions & 7 deletions base_rest/apispec/base_rest_service_apispec.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class BaseRestServiceAPISpec(APISpec):

def __init__(self, service_component, **params):
self._service = service_component
super(BaseRestServiceAPISpec, self).__init__(
super().__init__(
title="%s REST services" % self._service._usage,
version="",
openapi_version="3.0.0",
Expand All @@ -45,12 +45,7 @@ def _get_servers(self):
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,
)
"url": f"{base_url.strip('/')}/{collection_path.strip('/')}/{self._service._usage}"
}
]

Expand Down
8 changes: 3 additions & 5 deletions base_rest/apispec/rest_method_param_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,21 @@ class RestMethodParamPlugin(BasePlugin):
"""

def __init__(self, service):
super(RestMethodParamPlugin, self).__init__()
super().__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)
super().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_DECORATOR_ATTR)
if not routing:
super(RestMethodParamPlugin, self).operation_helper(
path, operations, **kwargs
)
super().operation_helper(path, operations, **kwargs)
if not operations:
return
for method, params in operations.items():
Expand Down
8 changes: 3 additions & 5 deletions base_rest/apispec/rest_method_security_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ class RestMethodSecurityPlugin(BasePlugin):
"""

def __init__(self, service, user_auths=("user",)):
super(RestMethodSecurityPlugin, self).__init__()
super().__init__()
self._service = service
self._supported_user_auths = user_auths

# pylint: disable=W8110
def init_spec(self, spec):
super(RestMethodSecurityPlugin, self).init_spec(spec)
super().init_spec(spec)
self.spec = spec
self.openapi_version = spec.openapi_version
user_scheme = {"type": "apiKey", "in": "cookie", "name": "session_id"}
Expand All @@ -27,9 +27,7 @@ def init_spec(self, spec):
def operation_helper(self, path=None, operations=None, **kwargs):
routing = kwargs.get(ROUTING_DECORATOR_ATTR)
if not routing:
super(RestMethodSecurityPlugin, self).operation_helper(
path, operations, **kwargs
)
super().operation_helper(path, operations, **kwargs)
if not operations:
return
auth = routing.get("auth", self.spec._params.get("default_auth"))
Expand Down
2 changes: 1 addition & 1 deletion base_rest/apispec/restapi_method_route_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class RestApiMethodRoutePlugin(BasePlugin):
"""

def __init__(self, service):
super(RestApiMethodRoutePlugin, self).__init__()
super().__init__()
self.converter_mapping = dict(DEFAULT_CONVERTER_MAPPING)
self._service = service

Expand Down
5 changes: 2 additions & 3 deletions base_rest/controllers/api_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,8 @@ def _get_api_urls(self):
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),
"name": f"{collection_path}: {service._usage}",
"url": f"/api-docs/{collection_path}/{service._usage}.json",
}
)
api_urls = sorted(api_urls, key=lambda k: k["name"])
Expand Down
2 changes: 1 addition & 1 deletion base_rest/controllers/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
_logger = logging.getLogger(__name__)


class _PseudoCollection(object):
class _PseudoCollection:
__slots__ = "_name", "env", "id"

def __init__(self, name, env):
Expand Down
8 changes: 4 additions & 4 deletions base_rest/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
try:
import pyquerystring
from accept_language import parse_accept_language
except (ImportError, IOError) as err:
except (OSError, ImportError) as err:
_logger.debug(err)


Expand All @@ -55,7 +55,7 @@ def default(self, obj): # pylint: disable=E0202,arguments-differ
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return float(obj)
return super(JSONEncoder, self).default(obj)
return super().default(obj)


BLACKLISTED_LOG_PARAMS = ("password",)
Expand Down Expand Up @@ -229,10 +229,10 @@ def handle_error(self, exception):
if isinstance(exception, MissingError):
extra_info = getattr(exception, "rest_json_info", None)
return wrapJsonException(NotFound(ustr(exception)), extra_info=extra_info)
if isinstance(exception, (AccessError, AccessDenied)):
if isinstance(exception, AccessError | AccessDenied):
extra_info = getattr(exception, "rest_json_info", None)
return wrapJsonException(Forbidden(ustr(exception)), extra_info=extra_info)
if isinstance(exception, (UserError, ValidationError)):
if isinstance(exception, UserError | ValidationError):
extra_info = getattr(exception, "rest_json_info", None)
return wrapJsonException(
BadRequest(exception.args[0]),
Expand Down
18 changes: 9 additions & 9 deletions base_rest/models/rest_service_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def _build_controller(self, service, controller_def):
)
base_controller_cls._identifier = identifier
# put our new controller into the new addon module
ctrl_cls.__module__ = "odoo.addons.{}".format(addon_name)
ctrl_cls.__module__ = f"odoo.addons.{addon_name}"

self.env.registry._init_modules.add(addon_name)

Expand Down Expand Up @@ -245,7 +245,7 @@ def _register_rest_route(self, route_path):
_rest_services_routes[self.env.cr.dbname].add(route_path)


class RestApiMethodTransformer(object):
class RestApiMethodTransformer:
"""Helper class to generate and apply the missing restapi.method decorator
to service's methods defined without decorator.
Expand Down Expand Up @@ -297,7 +297,7 @@ def _method_to_routes(self, method):
method_name = method.__name__
signature = inspect.signature(method)
id_in_path_required = "_id" in signature.parameters
path = "/{}".format(method_name)
path = f"/{method_name}"
if id_in_path_required:
path = "/<int:id>" + path
if method_name in ("get", "search"):
Expand Down Expand Up @@ -341,15 +341,15 @@ def _method_to_param(self, validator_method_name, direction):
return None

def _method_to_input_param(self, method):
validator_method_name = "_validator_{}".format(method.__name__)
validator_method_name = f"_validator_{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__)
validator_method_name = f"_validator_return_{method.__name__}"
return self._method_to_param(validator_method_name, "output")


class RestApiServiceControllerGenerator(object):
class RestApiServiceControllerGenerator:
"""
An object helper used to generate the http.Controller required to serve
the method decorated with the `@restappi.method` decorator
Expand Down Expand Up @@ -391,13 +391,13 @@ def _generate_methods(self):
path_sep = ""
if root_path[-1] != "/":
path_sep = "/"
root_path = "{}{}{}".format(root_path, path_sep, self._service._usage)
root_path = f"{root_path}{path_sep}{self._service._usage}"
for name, method in _inspect_methods(self._service.__class__):
routing = getattr(method, ROUTING_DECORATOR_ATTR, None)
if routing is None:
continue
for routes, http_method in routing["routes"]:
method_name = "{}_{}".format(http_method.lower(), name)
method_name = f"{http_method.lower()}_{name}"
default_route = routes[0]
rule = Rule(default_route)
Map(rules=[rule])
Expand All @@ -417,7 +417,7 @@ def _generate_methods(self):
exec(method, _globals)
method_exec = _globals[method_name]
route_params = dict(
route=["{}{}".format(root_path, r) for r in routes],
route=[f"{root_path}{r}" for r in routes],
methods=[http_method],
type="restapi",
)
Expand Down
3 changes: 3 additions & 0 deletions base_rest/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[build-system]
requires = ["whool"]
build-backend = "whool.buildapi"
2 changes: 1 addition & 1 deletion base_rest/restapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ def __init__(self, schema, min_items=None, max_items=None, unique_items=None):
contain unique items.
(Not enforced at validation time)
"""
super(CerberusListValidator, self).__init__(schema=schema)
super().__init__(schema=schema)
self._min_items = min_items
self._max_items = max_items
self._unique_items = unique_items
Expand Down
Loading

0 comments on commit 59d8d0a

Please sign in to comment.