Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[18.0][MIG] fastapi: Migration to 18.0 #471

Open
wants to merge 118 commits into
base: 18.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
118 commits
Select commit Hold shift + click to select a range
119a1ec
[ADD] Allows use of fastapi into Odoo!
lmignon Sep 23, 2022
04d86c4
[IMP] fastapi: Uses contextvars to hold and provide odoo env on fasta…
lmignon Sep 27, 2022
429da02
[IMP] fastapi: renames fastapi.app into fastapi.endpoint
lmignon Sep 28, 2022
f8d8c43
[IMP] fastapi: code cleanup
lmignon Oct 8, 2022
634dfd0
[IMP] fastapi: Improves modularity and demo app
lmignon Oct 8, 2022
50cfd6c
[IMP] fastapi: Add dependency method
lmignon Oct 9, 2022
ac0abb4
[IMP] fastapi: Implement error handling
lmignon Dec 7, 2022
d8e1037
[IMP] fastapi: Allows to define the user executing the api calls
lmignon Dec 10, 2022
7966964
[IMP] fastapi: Add authenticated_partner_id into ir.rule eval context
lmignon Dec 10, 2022
38f7bd6
[IMP] fastapi: Add helper code to ease development of search route ha…
lmignon Dec 10, 2022
a16a53d
[IMP] fastapi: documentation
lmignon Dec 10, 2022
d58e092
Fix a few typos
sbidoul Dec 10, 2022
e7ed75a
Fix typo
lmignon Dec 12, 2022
56bbee1
little fixes
lmignon Jan 27, 2023
2362418
[FIX] fastapi: Uses new implementation of endpoint_route_handler
lmignon Feb 24, 2023
21113bf
[FIX] fastapi: change annotation to support python 3.7+
lmignon Feb 24, 2023
f602324
[ADD] extendable_fastapi: New addon to allow the use of extendable wi…
lmignon Feb 24, 2023
11f317e
[FIX] fastapi: typo
lmignon Feb 26, 2023
a00388c
[IMP]fastapi: Uses the accept-languages header to determine the expex…
lmignon Feb 27, 2023
3b32e9e
[IMP] fastapi: Register only one handler by application
lmignon Feb 27, 2023
3bcd468
[IMP] fastapi: Improves UX for the endpoint registry synchronisation
lmignon Feb 27, 2023
8546eff
[IMP] fastapi: Improves documentation
lmignon Feb 27, 2023
59b6968
[IMP] fastapi: Improves documentation on security aspects
lmignon Mar 10, 2023
47f0f73
[IMP] fastapi: Declared as Beta
lmignon Apr 24, 2023
39692dd
[IMP] fastapi: Typos
lmignon Apr 24, 2023
01c3a2c
[UPD] Update fastapi.pot
Jun 7, 2023
3d1e645
[UPD] README.rst
OCA-git-bot Jun 7, 2023
d9c6aa5
[DOC] fast_api: fix _get_fastapi_routers documentation
sbidoul Jun 8, 2023
5abd8c6
[DOC] fastapi: documentation fixes
sbidoul Jun 8, 2023
21b7581
[UPD] README.rst
OCA-git-bot Jun 9, 2023
30ffa0e
[IMP] small changes in fastapi readme
AnizR Jun 11, 2023
eec5e5b
[UPD] README.rst
OCA-git-bot Jun 12, 2023
274091e
[IMP] fastapi: Add fastapi addons directory structure into documentation
lmignon Jun 14, 2023
be657f2
fixup! [IMP] fastapi: Add fastapi addons directory structure into doc…
lmignon Jun 14, 2023
121149e
fixup! fixup! [IMP] fastapi: Add fastapi addons directory structure i…
lmignon Jun 14, 2023
d3f7669
fixup! fixup! fixup! [IMP] fastapi: Add fastapi addons directory stru…
lmignon Jun 14, 2023
4b2d63b
fixup! fixup! fixup! fixup! [IMP] fastapi: Add fastapi addons directo…
lmignon Jun 14, 2023
90c6b24
fixup! fixup! fixup! fixup! fixup! [IMP] fastapi: Add fastapi addons …
lmignon Jun 14, 2023
4e50dd5
[UPD] README.rst
OCA-git-bot Jun 16, 2023
c6886d5
fastapi 16.0.0.0.2
OCA-git-bot Jun 16, 2023
22a6b88
[UPD] rest-framework : fix small typo in doc
xavier-bouquiaux Jun 21, 2023
1dd44a7
[UPD] README.rst
OCA-git-bot Jun 21, 2023
18cd618
[WIP] mount at root_path instead of adding prefixes
sbidoul Jun 23, 2023
dddb288
[IMP] fastapi: simplify tests a little bit
sbidoul Jun 23, 2023
75f4501
fastapi 16.0.0.0.3
OCA-git-bot Jun 26, 2023
1a33e46
[IMP] fastapi: Refactor demo app to follow dev guidelines
lmignon Jun 19, 2023
bbcc584
[IMP] fastapi: Add FastAPITransactionCase
lmignon Jun 19, 2023
6dfe2c2
[IMP] fastapi: Prefer typing.Annotated to describe method paramters
lmignon Jun 20, 2023
9b9f67b
[IMP] fastapi: Always run tests at post-install
lmignon Jun 26, 2023
244c076
[UPD] README.rst
OCA-git-bot Jun 28, 2023
08d1bff
fastapi 16.0.0.0.4
OCA-git-bot Jun 28, 2023
bf1ee94
fastapi: fix title underlines
sbidoul Jul 1, 2023
fa18a11
[UPD] README.rst
OCA-git-bot Jul 1, 2023
e32138c
Migration to Pydantic v2
lmignon Jul 24, 2023
6697505
[UPD] README.rst
OCA-git-bot Jul 25, 2023
13f04c6
fastapi 16.0.1.0.0
OCA-git-bot Jul 25, 2023
a0161a9
[IMP] fastapi: add company_id dependency override
marielejeune Jul 31, 2023
7cc71e8
[UPD] Update fastapi.pot
Jul 31, 2023
cefc899
fastapi 16.0.1.1.0
OCA-git-bot Jul 31, 2023
399a7e2
[ADD] extendable_fastapi: New class StrictExtendableBaseModel
marielejeune Jul 28, 2023
5e58e25
[UPD] README.rst
OCA-git-bot Aug 1, 2023
3c1b3d2
fastapi 16.0.1.1.1
OCA-git-bot Aug 1, 2023
b3d071d
[UPD] README.rst
OCA-git-bot Sep 3, 2023
6b04386
fix authenticated_partner_impl when no partner
Sep 11, 2023
53f1367
review change
Sep 25, 2023
b5e86f6
[BOT] post-merge updates
OCA-git-bot Sep 25, 2023
7af9e6d
[IMP] fastapi: Rename 'total' to 'count' into PagedCollection
lmignon Oct 12, 2023
4a2475b
[BOT] post-merge updates
OCA-git-bot Oct 13, 2023
f56a756
[FIX] fastapi: Field parameter typo in schemas.py
meestaben Nov 3, 2023
d3d38aa
[IMP] fastapi: Add news fragment to prepare release
lmignon Nov 3, 2023
d10d646
[BOT] post-merge updates
OCA-git-bot Nov 3, 2023
193fcf1
[MIG] mark all modules installable=False
sbidoul Nov 12, 2023
5cfb9b9
[FIX] fastapi: add "PATCH" method
astirpe Apr 17, 2024
cfb77f6
[FIX] fastapi: In test class don't override overrides
lmignon Nov 13, 2023
6950a0b
[BOT] post-merge updates
OCA-git-bot Dec 12, 2023
ddc7c40
[FIX] fastapi: close cursor after rollback
sbidoul Dec 18, 2023
650226c
[BOT] post-merge updates
OCA-git-bot Dec 21, 2023
fdd3b7c
Revert "[FIX] fastapi: close cursor after rollback"
sbidoul Dec 21, 2023
a0a399d
[BOT] post-merge updates
OCA-git-bot Dec 21, 2023
fd96254
Added translation using Weblate (Italian)
mymage Jan 10, 2024
3979683
Translated using Weblate (Italian)
mymage Jan 15, 2024
dbde6a7
[16.0][FIX] fastapi: always add authenticate_partner_id in context wh…
AnizR Jan 12, 2024
ff847c7
[BOT] post-merge updates
OCA-git-bot Jan 17, 2024
a69680b
[FIX] fastapi: Compatibility with latest Odoo
lmignon Feb 20, 2024
b7c8e0e
[MIG] fastapi: Migration to 17.0
nguyenminhchien May 24, 2024
3394772
[UPD] Update fastapi.pot
Jun 6, 2024
5e5aa1a
[BOT] post-merge updates
OCA-git-bot Jun 6, 2024
0180ae3
Update translation files
weblate Jun 6, 2024
5af0d89
[FIX] fastapi: Consolidating licenses inside the fastapi modue to LGPL-3
mfalatec Aug 21, 2024
224eed4
[FIX] fastapi: History file content
lmignon Oct 1, 2024
68c26b5
[BOT] post-merge updates
OCA-git-bot Oct 1, 2024
870b32b
[FIX] fastapi: Handle error occurring outside the fastapi processing
lmignon Mar 14, 2024
f9adb3d
[BOT] post-merge updates
OCA-git-bot Oct 2, 2024
64294c2
fastapi: improve test client setup
simahawk Apr 8, 2024
71b889d
[IMP] fastapi: Optionally authenticated partner
lmignon Oct 31, 2023
a06d4e4
[FIX] fastapi: Enable auto retry of calls
lmignon Mar 15, 2024
df7e3f2
[IMP] fastapi: Add Exception handler for IntegrityError
lmignon Mar 15, 2024
976bb28
[IMP] fastatpi: Add tests for the retrying mechanism
lmignon Mar 18, 2024
489ac4e
[FIX] fastapi: Readme
lmignon Mar 15, 2024
3420325
[FIX] fastapi: Transactions handling refactoring
lmignon Mar 19, 2024
e61c04a
[BOT] post-merge updates
OCA-git-bot Oct 3, 2024
0e7d252
[FIX] fastapi: Avoid process stuck in case of retry of Post request w…
lmignon Jun 26, 2024
16b7bd3
[FIX] fastapi: Fix minimal version for ext dependencies
lmignon Jun 27, 2024
2fb5fc0
[IMP] fastapi: Simplified code and improved perfs
lmignon Jun 28, 2024
686ea49
[16.0][FIX] fastapi: paging - correctly set authorised minimal value …
AnizR Aug 8, 2024
0281b0d
[FIX] fastapi: Unflag save_session in routing info
paradoxxxzero Jul 9, 2024
57e1619
[IMP] fastapi: Makes the save_session configurable
lmignon Oct 1, 2024
d0b4047
[LINT] fastapi
paradoxxxzero Oct 1, 2024
7259487
[UPD] Update fastapi.pot
Oct 3, 2024
6fc9efe
[BOT] post-merge updates
OCA-git-bot Oct 3, 2024
ed53f63
Update translation files
weblate Oct 3, 2024
a4d74a2
Translated using Weblate (Italian)
mymage Oct 4, 2024
a6e88ca
[IMP] fastapi: Factorize error handling and use it in tests with rai…
paradoxxxzero Oct 16, 2024
dbd339a
[BOT] post-merge updates
OCA-git-bot Oct 16, 2024
7f2b580
[IMP] fastapi: pre-commit auto fixes
cormaza Nov 8, 2024
5353ef2
[18.0][MIG] fastapi: Migration to 18.0
cormaza Nov 8, 2024
d960109
[PATCH] [FIX] fastapi: Disable exception logger when exception is exp…
cormaza Nov 19, 2024
57944ca
[18.0][FIX] fastapi, use new authenticate signature and dict answer
cormaza Dec 11, 2024
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
1,675 changes: 1,675 additions & 0 deletions fastapi/README.rst

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions fastapi/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from . import models
from . import fastapi_dispatcher
from . import error_handlers
34 changes: 34 additions & 0 deletions fastapi/__manifest__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Copyright 2022 ACSONE SA/NV
# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL).

{
"name": "Odoo FastAPI",
"summary": """
Odoo FastAPI endpoint""",
"version": "18.0.1.0.0",
"license": "LGPL-3",
"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",
"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",
"python-multipart",
"ujson",
"a2wsgi>=1.10.6",
"parse-accept-language",
]
},
"development_status": "Beta",
"installable": True,
}
10 changes: 10 additions & 0 deletions fastapi/context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Copyright 2022 ACSONE SA/NV
# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL).

# define context vars to hold the odoo env

from contextvars import ContextVar

from odoo.api import Environment

odoo_env_ctx: ContextVar[Environment] = ContextVar("odoo_env_ctx")
47 changes: 47 additions & 0 deletions fastapi/demo/fastapi_endpoint_demo.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?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>
<!-- This is the user that will be used to run the demo app -->
<record
id="my_demo_app_user"
model="res.users"
context="{'no_reset_password': True, 'no_reset_password': True}"
>
<field name="name">My Demo Endpoint User</field>
<field name="login">my_demo_app_user</field>
<field name="groups_id" eval="[(6, 0, [])]" />
</record>

<!-- This is the group that will be used to run the demo app
This group will only depend on the "group_fastapi_endpoint_runner" group
that provides the minimal access rights to retrieve the user running the
endpoint handlers and performs authentication.
-->
<record id="my_demo_app_group" model="res.groups">
<field name="name">My Demo Endpoint Group</field>
<field name="users" eval="[(4, ref('my_demo_app_user'))]" />
<field name="implied_ids" eval="[(4, ref('group_fastapi_endpoint_runner'))]" />
</record>

<!-- This is the endpoint that will be used to run the demo app
This endpoint will be registered on the "/fastapi_demo" path
-->

<record model="fastapi.endpoint" id="fastapi_endpoint_demo">
<field name="name">Fastapi Demo Endpoint</field>
<field
name="description"
><![CDATA[
# A Dummy FastApi Demo

This demo endpoint has been created by inhering from "fastapi.endpoint", registering
a new app into the app selection field and implementing the `_get_fastapi_routers`
methods. See documentation to learn more about how to create a new app.
]]></field>
<field name="app">demo</field>
<field name="root_path">/fastapi_demo</field>
<field name="demo_auth_method">http_basic</field>
<field name="user_id" ref="my_demo_app_user" />
</record>
</odoo>
177 changes: 177 additions & 0 deletions fastapi/dependencies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# Copyright 2022 ACSONE SA/NV
# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL).

from typing import TYPE_CHECKING, Annotated

from odoo.api import Environment
from odoo.exceptions import AccessDenied

from odoo.addons.base.models.res_partner import Partner
from odoo.addons.base.models.res_users import Users

from fastapi import Depends, Header, HTTPException, Query, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials

from .context import odoo_env_ctx
from .schemas import Paging

if TYPE_CHECKING:
from .models.fastapi_endpoint import FastapiEndpoint

Check warning on line 19 in fastapi/dependencies.py

View check run for this annotation

Codecov / codecov/patch

fastapi/dependencies.py#L19

Added line #L19 was not covered by tests


def company_id() -> int | None:
"""This method may be overriden by the FastAPI app to set the allowed company
in the Odoo env of the endpoint. By default, the company defined on the
endpoint record is used.
"""
return None

Check warning on line 27 in fastapi/dependencies.py

View check run for this annotation

Codecov / codecov/patch

fastapi/dependencies.py#L27

Added line #L27 was not covered by tests


def odoo_env(company_id: Annotated[int | None, Depends(company_id)]) -> Environment:
env = odoo_env_ctx.get()
if company_id is not None:
env = env(context=dict(env.context, allowed_company_ids=[company_id]))

yield env


def authenticated_partner_impl() -> Partner:
"""This method has to be overriden when you create your fastapi app
to declare the way your partner will be provided. In some case, this
partner will come from the authentication mechanism (ex jwt token) in other cases
it could comme from a lookup on an email received into an HTTP header ...
See the fastapi_endpoint_demo for an example"""


def optionally_authenticated_partner_impl() -> Partner | None:
"""This method has to be overriden when you create your fastapi app
and you need to get an optional authenticated partner into your endpoint.
"""


def authenticated_partner_env(
partner: Annotated[Partner, Depends(authenticated_partner_impl)],
) -> Environment:
"""Return an environment with the authenticated partner id in the context"""
return partner.with_context(authenticated_partner_id=partner.id).env


def optionally_authenticated_partner_env(
partner: Annotated[Partner | None, Depends(optionally_authenticated_partner_impl)],
env: Annotated[Environment, Depends(odoo_env)],
) -> Environment:
"""Return an environment with the authenticated partner id in the context if
the partner is not None
"""
if partner:
return partner.with_context(authenticated_partner_id=partner.id).env
return env

Check warning on line 68 in fastapi/dependencies.py

View check run for this annotation

Codecov / codecov/patch

fastapi/dependencies.py#L67-L68

Added lines #L67 - L68 were not covered by tests


def authenticated_partner(
partner: Annotated[Partner, Depends(authenticated_partner_impl)],
partner_env: Annotated[Environment, Depends(authenticated_partner_env)],
) -> Partner:
"""If you need to get access to the authenticated partner into your
endpoint, you can add a dependency into the endpoint definition on this
method.
This method is a safe way to declare a dependency without requiring a
specific implementation. It depends on `authenticated_partner_impl`. The
concrete implementation of authenticated_partner_impl has to be provided
when the FastAPI app is created.
This method return a partner into the authenticated_partner_env
"""
return partner_env["res.partner"].browse(partner.id)


def optionally_authenticated_partner(
partner: Annotated[Partner | None, Depends(optionally_authenticated_partner_impl)],
partner_env: Annotated[Environment, Depends(optionally_authenticated_partner_env)],
) -> Partner | None:
"""If you need to get access to the authenticated partner if the call is
authenticated, you can add a dependency into the endpoint definition on this
method.

This method defer from authenticated_partner by the fact that it returns
None if the partner is not authenticated .
"""
if partner:
return partner_env["res.partner"].browse(partner.id)
return None

Check warning on line 100 in fastapi/dependencies.py

View check run for this annotation

Codecov / codecov/patch

fastapi/dependencies.py#L99-L100

Added lines #L99 - L100 were not covered by tests


def paging(
page: Annotated[int, Query(ge=1)] = 1, page_size: Annotated[int, Query(ge=1)] = 80
) -> Paging:
"""Return a Paging object from the page and page_size parameters"""
return Paging(limit=page_size, offset=(page - 1) * page_size)

Check warning on line 107 in fastapi/dependencies.py

View check run for this annotation

Codecov / codecov/patch

fastapi/dependencies.py#L107

Added line #L107 was not covered by tests


def basic_auth_user(
credential: Annotated[HTTPBasicCredentials, Depends(HTTPBasic())],
env: Annotated[Environment, Depends(odoo_env)],
) -> Users:
username = credential.username
password = credential.password
try:
response = (

Check warning on line 117 in fastapi/dependencies.py

View check run for this annotation

Codecov / codecov/patch

fastapi/dependencies.py#L114-L117

Added lines #L114 - L117 were not covered by tests
env["res.users"]
.sudo()
.authenticate(
db=env.cr.dbname,
credential={
"type": "password",
"login": username,
"password": password,
},
user_agent_env=None,
)
)
return env["res.users"].browse(response.get("uid"))
except AccessDenied as ad:
raise HTTPException(

Check warning on line 132 in fastapi/dependencies.py

View check run for this annotation

Codecov / codecov/patch

fastapi/dependencies.py#L130-L132

Added lines #L130 - L132 were not covered by tests
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
) from ad


def authenticated_partner_from_basic_auth_user(
user: Annotated[Users, Depends(basic_auth_user)],
env: Annotated[Environment, Depends(odoo_env)],
) -> Partner:
return env["res.partner"].browse(user.sudo().partner_id.id)

Check warning on line 143 in fastapi/dependencies.py

View check run for this annotation

Codecov / codecov/patch

fastapi/dependencies.py#L143

Added line #L143 was not covered by tests


def fastapi_endpoint_id() -> int:
"""This method is overriden by the FastAPI app to make the fastapi.endpoint record
available for your endpoint method. To get the fastapi.endpoint record
in your method, you just need to add a dependency on the fastapi_endpoint method
defined below
"""


def fastapi_endpoint(
_id: Annotated[int, Depends(fastapi_endpoint_id)],
env: Annotated[Environment, Depends(odoo_env)],
) -> "FastapiEndpoint":
"""Return the fastapi.endpoint record"""
return env["fastapi.endpoint"].browse(_id)

Check warning on line 159 in fastapi/dependencies.py

View check run for this annotation

Codecov / codecov/patch

fastapi/dependencies.py#L159

Added line #L159 was not covered by tests


def accept_language(
accept_language: Annotated[
str | None,
Header(
alias="Accept-Language",
description="The Accept-Language header is used to specify the language "
"of the content to be returned. If a language is not available, the "
"server will return the content in the default language.",
),
] = None,
) -> str:
"""This dependency is used at application level to document the way the language
to use for the response is specified. The header is processed outside of the
fastapi app to initialize the odoo environment with the right language.
"""
return accept_language
12 changes: 12 additions & 0 deletions fastapi/depends.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Copyright 2023 ACSONE SA/NV
# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL).

import warnings

warnings.warn(
"The 'depends' package is deprecated. Please use 'dependencies' instead.",
DeprecationWarning,
stacklevel=2,
)

from .dependencies import * # noqa: F403, F401, E402
77 changes: 77 additions & 0 deletions fastapi/error_handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Copyright 2022 ACSONE SA/NV
# License LGPL-3.0 or later (http://www.gnu.org/licenses/LGPL).

from starlette import status
from starlette.exceptions import HTTPException, WebSocketException
from starlette.middleware.errors import ServerErrorMiddleware
from starlette.middleware.exceptions import ExceptionMiddleware
from starlette.responses import JSONResponse
from starlette.websockets import WebSocket
from werkzeug.exceptions import HTTPException as WerkzeugHTTPException

from odoo.exceptions import AccessDenied, AccessError, MissingError, UserError

from fastapi import Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
from fastapi.utils import is_body_allowed_for_status_code


def convert_exception_to_status_body(exc: Exception) -> tuple[int, dict]:
body = {}
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
details = "Internal Server Error"

if isinstance(exc, WerkzeugHTTPException):
status_code = exc.code
details = exc.description

Check warning on line 27 in fastapi/error_handlers.py

View check run for this annotation

Codecov / codecov/patch

fastapi/error_handlers.py#L26-L27

Added lines #L26 - L27 were not covered by tests
elif isinstance(exc, HTTPException):
status_code = exc.status_code
details = exc.detail
elif isinstance(exc, RequestValidationError):
status_code = status.HTTP_422_UNPROCESSABLE_ENTITY
details = jsonable_encoder(exc.errors())
elif isinstance(exc, WebSocketRequestValidationError):
status_code = status.WS_1008_POLICY_VIOLATION
details = jsonable_encoder(exc.errors())

Check warning on line 36 in fastapi/error_handlers.py

View check run for this annotation

Codecov / codecov/patch

fastapi/error_handlers.py#L35-L36

Added lines #L35 - L36 were not covered by tests
elif isinstance(exc, AccessDenied | AccessError):
status_code = status.HTTP_403_FORBIDDEN
details = "AccessError"
elif isinstance(exc, MissingError):
status_code = status.HTTP_404_NOT_FOUND
details = "MissingError"
elif isinstance(exc, UserError):
status_code = status.HTTP_400_BAD_REQUEST
details = exc.args[0]

if is_body_allowed_for_status_code(status_code):
# use the same format as in
# fastapi.exception_handlers.http_exception_handler
body = {"detail": details}
return status_code, body


# we need to monkey patch the ServerErrorMiddleware and ExceptionMiddleware classes
# to ensure that all the exceptions that are handled by these specific
# middlewares are let to bubble up to the retrying mechanism and the
# dispatcher error handler to ensure that appropriate action are taken
# regarding the transaction, environment, and registry. These middlewares
# are added by default by FastAPI when creating an application and it's not
# possible to remove them. So we need to monkey patch them.


def pass_through_exception_handler(
self, request: Request, exc: Exception
) -> JSONResponse:
raise exc


def pass_through_websocket_exception_handler(
self, websocket: WebSocket, exc: WebSocketException
) -> None:
raise exc

Check warning on line 72 in fastapi/error_handlers.py

View check run for this annotation

Codecov / codecov/patch

fastapi/error_handlers.py#L72

Added line #L72 was not covered by tests


ServerErrorMiddleware.error_response = pass_through_exception_handler
ExceptionMiddleware.http_exception = pass_through_exception_handler
ExceptionMiddleware.websocket_exception = pass_through_websocket_exception_handler
Loading
Loading