Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
exclude: |
(?x)
# NOT INSTALLABLE ADDONS
^base_rest/|
^base_rest_auth_api_key/|
^base_rest_pydantic/|
^extendable/|
^pydantic/|
^rest_log/|
# END NOT INSTALLABLE ADDONS
# Files and folders generated by bots, to avoid loops
^setup/|/static/description/index\.html$|
Expand Down
21 changes: 15 additions & 6 deletions fastapi/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Odoo FastAPI
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:7f952481ecfa343c890ca430608d4fbca7de214b8c18c77a011d2b095ea214b0
!! source digest: sha256:41dedec55c75773771ea473537c0396eba410d46b1a7b97dad61fcb776bd228c
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
Expand All @@ -21,13 +21,13 @@ Odoo FastAPI
:target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html
:alt: License: LGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Frest--framework-lightgray.png?logo=github
:target: https://github.com/OCA/rest-framework/tree/19.0/fastapi
:target: https://github.com/OCA/rest-framework/tree/20.0/fastapi
:alt: OCA/rest-framework
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/rest-framework-19-0/rest-framework-19-0-fastapi
:target: https://translation.odoo-community.org/projects/rest-framework-20-0/rest-framework-20-0-fastapi
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/rest-framework&target_branch=19.0
:target: https://runboat.odoo-community.org/builds?repo=OCA/rest-framework&target_branch=20.0
:alt: Try me on Runboat

|badge1| |badge2| |badge3| |badge4| |badge5|
Expand Down Expand Up @@ -263,6 +263,12 @@ Now, you can start your Odoo server, install your addon and create a new
endpoint instance for your app. Once it's done click on the docs url to
access the interactive documentation of your app.

**Note**: FastAPI automatically exposes three services to easily
interact with the APIs and their structure (Swagger, Redoc, OpenAPI).
When exposing your Odoo instance to the open internet you might want to
disable these services. To do so toggle the "Expose FastAPI docs"
checkbox in the FastAPI Endpoint form view.

Before trying to test your app, you need to define on the endpoint
instance the user that will be used to run the app. You can do it by
setting the **'user_id'** field. This information is the most important
Expand Down Expand Up @@ -1636,7 +1642,7 @@ Bug Tracker
Bugs are tracked on `GitHub Issues <https://github.com/OCA/rest-framework/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/rest-framework/issues/new?body=module:%20fastapi%0Aversion:%2019.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
`feedback <https://github.com/OCA/rest-framework/issues/new?body=module:%20fastapi%0Aversion:%2020.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.

Do not contact contributors directly about support or help with technical issues.

Expand All @@ -1653,6 +1659,9 @@ Contributors

- Laurent Mignon <[email protected]>
- Lois Rilo <[email protected]>
- Open2S (https://www.open2s.com.ec):

- Danilo Moya <[email protected]>

Maintainers
-----------
Expand All @@ -1675,6 +1684,6 @@ Current `maintainer <https://odoo-community.org/page/maintainer-role>`__:

|maintainer-lmignon|

This module is part of the `OCA/rest-framework <https://github.com/OCA/rest-framework/tree/19.0/fastapi>`_ project on GitHub.
This module is part of the `OCA/rest-framework <https://github.com/OCA/rest-framework/tree/20.0/fastapi>`_ project on GitHub.

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
15 changes: 7 additions & 8 deletions fastapi/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,31 @@

{
"name": "Odoo FastAPI",
"summary": """
Odoo FastAPI endpoint""",
"version": "19.0.1.1.0",
"summary": "Odoo FastAPI endpoint",
"version": "20.0.1.0.0",
"license": "LGPL-3",
"author": "ACSONE SA/NV,Odoo Community Association (OCA)",
"author": "ACSONE SA/NV, Odoo Community Association (OCA)",
"maintainers": ["lmignon"],
"website": "https://github.com/OCA/rest-framework",
"depends": ["endpoint_route_handler"],
"data": [
"security/res_groups.xml",
"security/fastapi_endpoint.xml",
"security/ir_rule+acl.xml",
"security/ir.access.csv",
"views/fastapi_menu.xml",
"views/fastapi_endpoint.xml",
"views/fastapi_endpoint_demo.xml",
],
"demo": ["demo/fastapi_endpoint_demo.xml"],
"external_dependencies": {
"python": [
"fastapi>=0.110.0",
"fastapi",
"python-multipart",
"ujson",
"a2wsgi>=1.10.6",
"parse-accept-language",
"fastapi-openapi-overrides",
]
},
"development_status": "Beta",
"installable": False,
"installable": True,
}
4 changes: 2 additions & 2 deletions fastapi/demo/fastapi_endpoint_demo.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Copyright 2022 ACSONE SA/NV
License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL). -->
<odoo>
Expand Down Expand Up @@ -31,7 +31,7 @@
This endpoint will be registered on the "/fastapi_demo" path
-->

<record model="fastapi.endpoint" id="fastapi_endpoint_demo">
<record id="fastapi_endpoint_demo" model="fastapi.endpoint">
<field name="name">Fastapi Demo Endpoint</field>
<field
name="description"
Expand Down
2 changes: 1 addition & 1 deletion fastapi/depends.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@
stacklevel=2,
)

from .dependencies import * # noqa: F403, F401, E402
from .dependencies import *
7 changes: 6 additions & 1 deletion fastapi/fastapi_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
from contextlib import contextmanager
from io import BytesIO

from odoo.http import Dispatcher, request
from odoo.http import request

try:
from odoo.http.dispatcher import Dispatcher
except ImportError:
from odoo.http import Dispatcher

from .context import odoo_env_ctx
from .error_handlers import convert_exception_to_status_body
Expand Down
5 changes: 5 additions & 0 deletions fastapi/i18n/fastapi.pot
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ msgstr ""
msgid "Docs Url"
msgstr ""

#. module: fastapi
#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__expose_doc_urls
msgid "Expose FastAPI docs"
msgstr ""

#. module: fastapi
#: model:ir.module.category,name:fastapi.module_category_fastapi
#: model:ir.ui.menu,name:fastapi.menu_fastapi_root
Expand Down
5 changes: 5 additions & 0 deletions fastapi/i18n/it.po
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ msgstr "Nome visualizzato"
msgid "Docs Url"
msgstr "URL documenti"

#. module: fastapi
#: model:ir.model.fields,field_description:fastapi.field_fastapi_endpoint__expose_doc_urls
msgid "Expose FastAPI docs"
msgstr ""

#. module: fastapi
#: model:ir.module.category,name:fastapi.module_category_fastapi
#: model:ir.ui.menu,name:fastapi.menu_fastapi_root
Expand Down
31 changes: 16 additions & 15 deletions fastapi/models/fastapi_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
from collections.abc import Callable
from functools import partial
from itertools import chain
from typing import Any
from typing import Any, ClassVar

from fastapi_openapi_overrides import document_dependency_overrides
from starlette.middleware import Middleware
from starlette.routing import Mount

from odoo import api, exceptions, fields, models, tools
from odoo import api, exceptions, fields, models
from odoo.tools import convert

from fastapi import APIRouter, Depends, FastAPI
Expand Down Expand Up @@ -41,7 +42,6 @@ class FastapiEndpoint(models.Model):
app: str = fields.Selection(selection=[], required=True)
user_id = fields.Many2one(
comodel_name="res.users",
string="User",
help="The user to use to execute the API calls.",
default=lambda self: self.env.ref("base.public_user"),
)
Expand All @@ -66,6 +66,7 @@ class FastapiEndpoint(models.Model):
default=True,
)
route_group = fields.Char(help="Use this to classify routes together", size=32)
expose_doc_urls = fields.Boolean("Expose FastAPI docs", default=True)

@api.depends("root_path")
def _compute_root_path(self):
Expand All @@ -82,7 +83,7 @@ def _clean_root_path(self):
root_path = "/" + root_path
return root_path

_blacklist_root_paths = {"/", "/web", "/website"}
_blacklist_root_paths: ClassVar[set[str]] = {"/", "/web", "/website"}

@api.constrains("root_path")
def _check_root_path(self):
Expand Down Expand Up @@ -141,7 +142,7 @@ def action_sync_registry(self):

def _handle_route_updates(self, vals):
observed_fields = [self._routing_impacting_fields(), self._fastapi_app_fields()]
refresh_fastapi_app = any([x in vals for x in chain(*observed_fields)])
refresh_fastapi_app = any(x in vals for x in chain(*observed_fields))
if refresh_fastapi_app:
self._reset_app()
if "user_id" in vals:
Expand All @@ -151,7 +152,7 @@ def _handle_route_updates(self, vals):
@api.model
def _fastapi_app_fields(self) -> list[str]:
"""The list of fields requiring to refresh the fastapi app if modified"""
return []
return ["expose_doc_urls"]

def _make_routing_rule(self, options=None):
"""Generator of rule"""
Expand Down Expand Up @@ -229,11 +230,7 @@ def _is_suburl(self, path, prefix) -> bool:
path = self._normalize_url_path(path)
prefix = self._normalize_url_path(prefix)

if path == prefix:
return True
if path.startswith(prefix + "/"):
return True
return False
return path == prefix or bool(path.startswith(prefix + "/"))

@api.model
def _find_first_matching_url_path(self, paths, prefix) -> str | None:
Expand All @@ -254,12 +251,12 @@ def _find_first_matching_url_path(self, paths, prefix) -> str | None:
return None

@api.model
@tools.ormcache()
@api.ormcache()
def _get_id_by_root_path_map(self):
return {r.root_path: r.id for r in self.search([])}

@api.model
@tools.ormcache("path")
@api.ormcache("path")
def _get_id_for_path(self, path):
id_by_path = self._get_id_by_root_path_map()
root_path = self._find_first_matching_url_path(id_by_path.keys(), path)
Expand Down Expand Up @@ -296,7 +293,7 @@ def _clear_fastapi_exception_handlers(self, app: FastAPI) -> None:
self._clear_fastapi_exception_handlers(route.app)

@api.model
@tools.ormcache("path")
@api.ormcache("path")
def get_uid(self, path):
record = self._get_endpoint(path)
if not record:
Expand All @@ -308,6 +305,7 @@ def _get_app(self) -> FastAPI:
for router in self._get_fastapi_routers():
app.include_router(router=router)
app.dependency_overrides.update(self._get_app_dependencies_overrides())
document_dependency_overrides(app)
return app

def _get_app_dependencies_overrides(self) -> dict[Callable, Callable]:
Expand All @@ -321,12 +319,15 @@ def _get_app_dependencies_overrides(self) -> dict[Callable, Callable]:

def _prepare_fastapi_app_params(self) -> dict[str, Any]:
"""Return the params to pass to the Fast API app constructor"""
return {
to_return = {
"title": self.name,
"description": self.description,
"middleware": self._get_fastapi_app_middlewares(),
"dependencies": self._get_fastapi_app_dependencies(),
}
if not self.expose_doc_urls:
to_return |= {"docs_url": None, "redoc_url": None, "openapi_url": None}
return to_return

def _get_fastapi_routers(self) -> list[APIRouter]:
"""Return the api routers to use for the instance.
Expand Down
17 changes: 6 additions & 11 deletions fastapi/models/ir_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,10 @@
from odoo import api, models


class IrRule(models.Model):
"""Add authenticated_partner_id in record rule evaluation context.
class IrAccess(models.Model):
"""Add authenticated_partner_id in record rule/access evaluation context."""

This come from the env current odoo environment which is
populated by dependency method authenticated_partner_env or authenticated_partner
when a route handler depends one of them and is called by the FastAPI service layer.
"""

_inherit = "ir.rule"
_inherit = "ir.access"

@api.model
def _eval_context(self):
Expand All @@ -22,6 +17,6 @@ def _eval_context(self):
)
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"]
def _get_access_context(self):
yield from super()._get_access_context()
yield self.env.context.get("authenticated_partner_id")
4 changes: 2 additions & 2 deletions fastapi/models/res_lang.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@

from accept_language import parse_accept_language

from odoo import api, models, tools
from odoo import api, models


class ResLang(models.Model):
_inherit = "res.lang"

@api.model
@tools.ormcache("accept_language")
@api.ormcache("accept_language")
def _get_lang_from_accept_language(self, accept_language):
"""Get the language from the Accept-Language header.

Expand Down
31 changes: 14 additions & 17 deletions fastapi/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,26 @@

from urllib.parse import parse_qs, urlparse

from odoo.http import Request, db_filter
import odoo.http.router as http_router
from odoo.http.router import db_filter

_original_get_session_and_dbname = Request._get_session_and_dbname
_original_set_session_and_dbname = http_router._set_session_and_dbname


def _patched_get_session_and_dbname(self):
session, dbname = _original_get_session_and_dbname(self)
if not dbname:
# Try to get the database from request "db" param.
# This is useful for multi-database environments.
db = self.httprequest.args.get("db", "").strip()
def _patched_set_session_and_dbname(request):
_original_set_session_and_dbname(request)
if not getattr(request, "db", None):
db = request.httprequest.args.get("db", "").strip()
if not db:
# For browser sub-requests (e.g. openapi.json or static assets fetched
# by Swagger UI / ReDoc), the browser sets a Referer header pointing
# to the docs page which may carry the "db" query parameter.
referer = self.httprequest.headers.get("Referer", "")
referer = request.httprequest.headers.get("Referer", "")
if referer:
parsed = urlparse(referer)
db = parse_qs(parsed.query).get("db", [""])[0].strip()
if db and db_filter([db]):
dbname = db
session.db = dbname
return session, dbname
host = request.httprequest.environ.get("HTTP_HOST", "")
if db and db_filter([db], host=host):
request.db = db
if hasattr(request, "session") and request.session:
request.session.db = db


Request._get_session_and_dbname = _patched_get_session_and_dbname
http_router._set_session_and_dbname = _patched_set_session_and_dbname
Loading
Loading