Skip to content

[16.0][IMP]fastapi: enable multi-slash routes #515

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

Merged
merged 4 commits into from
Jun 25, 2025
Merged
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
11 changes: 11 additions & 0 deletions fastapi/demo/fastapi_endpoint_demo.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,15 @@ methods. See documentation to learn more about how to create a new app.
<field name="demo_auth_method">http_basic</field>
<field name="user_id" ref="my_demo_app_user" />
</record>

<record id="fastapi_endpoint_multislash_demo" model="fastapi.endpoint">
<field name="name">Fastapi Multi-Slash Demo Endpoint</field>
<field name="description">
Like the other demo endpoint but with multi-slash
</field>
<field name="app">demo</field>
<field name="root_path">/fastapi/demo-multi</field>
<field name="demo_auth_method">http_basic</field>
<field name="user_id" ref="my_demo_app_user" />
</record>
</odoo>
6 changes: 3 additions & 3 deletions fastapi/fastapi_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ def dispatch(self, endpoint, args):
# don't parse the httprequest let starlette parse the stream
self.request.params = {} # dict(self.request.get_http_params(), **args)
environ = self._get_environ()
root_path = "/" + environ["PATH_INFO"].split("/")[1]
path = environ["PATH_INFO"]
# TODO store the env into contextvar to be used by the odoo_env
# depends method
with fastapi_app_pool.get_app(env=request.env, root_path=root_path) as app:
uid = request.env["fastapi.endpoint"].sudo().get_uid(root_path)
with fastapi_app_pool.get_app(env=request.env, root_path=path) as app:
uid = request.env["fastapi.endpoint"].sudo().get_uid(path)
data = BytesIO()
with self._manage_odoo_env(uid):
for r in app(environ, self._make_response):
Expand Down
75 changes: 70 additions & 5 deletions fastapi/models/fastapi_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@
return f"{self._name}:{self.id}:{path}"

def _reset_app(self):
self._get_id_by_root_path_map.clear_cache(self)
self._get_id_for_path.clear_cache(self)

Check warning on line 202 in fastapi/models/fastapi_endpoint.py

View check run for this annotation

Codecov / codecov/patch

fastapi/models/fastapi_endpoint.py#L201-L202

Added lines #L201 - L202 were not covered by tests
self._reset_app_cache_marker.clear_cache(self)

@tools.ormcache()
Expand All @@ -211,8 +213,71 @@
"""

@api.model
def get_app(self, root_path):
record = self.search([("root_path", "=", root_path)])
def _normalize_url_path(self, path) -> str:
"""
Normalize a URL path:
* Remove redundant slashes,
* Remove trailing slash (unless it's the root),
* Lowercase for case-insensitive matching
"""
parts = [part.lower() for part in path.strip().split("/") if part]
return "/" + "/".join(parts)

@api.model
def _is_suburl(self, path, prefix) -> bool:
"""
Check if 'path' is a subpath of 'prefix' in URL logic:
* Must start with the prefix followed by a slash
This will ensure that the matching is done one the path
parts and ensures that e.g. /a/b is not prefix of /a/bc.
"""
path = self._normalize_url_path(path)
prefix = self._normalize_url_path(prefix)

if path == prefix:
return True

Check warning on line 238 in fastapi/models/fastapi_endpoint.py

View check run for this annotation

Codecov / codecov/patch

fastapi/models/fastapi_endpoint.py#L238

Added line #L238 was not covered by tests
if path.startswith(prefix + "/"):
return True
return False

@api.model
def _find_first_matching_url_path(self, paths, prefix) -> str | None:
"""
Return the first path that is a subpath of 'prefix',
ordered by longest URL path first (most number of segments).
"""
# Sort by number of segments (shallowest first)
sorted_paths = sorted(
paths,
key=lambda p: len(self._normalize_url_path(p).split("/")),
reverse=True,
)

for path in sorted_paths:
if self._is_suburl(prefix, path):
return path
return None

Check warning on line 259 in fastapi/models/fastapi_endpoint.py

View check run for this annotation

Codecov / codecov/patch

fastapi/models/fastapi_endpoint.py#L259

Added line #L259 was not covered by tests

@api.model
@tools.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")
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)
return id_by_path.get(root_path)

@api.model
def _get_endpoint(self, path):
id_ = self._get_id_for_path(path)
return self.browse(id_) if id_ else None

@api.model
def get_app(self, path):
record = self._get_endpoint(path)
if not record:
return None
app = FastAPI()
Expand All @@ -236,9 +301,9 @@
self._clear_fastapi_exception_handlers(route.app)

@api.model
@tools.ormcache("root_path")
def get_uid(self, root_path):
record = self.search([("root_path", "=", root_path)])
@tools.ormcache("path")
def get_uid(self, path):
record = self._get_endpoint(path)
if not record:
return None
return record.user_id.id
Expand Down
32 changes: 31 additions & 1 deletion fastapi/tests/test_fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ class FastAPIHttpCase(HttpCase):
def setUpClass(cls):
super().setUpClass()
cls.fastapi_demo_app = cls.env.ref("fastapi.fastapi_endpoint_demo")
cls.fastapi_demo_app._handle_registry_sync()
cls.fastapi_multi_demo_app = cls.env.ref(
"fastapi.fastapi_endpoint_multislash_demo"
)
cls.fastapi_apps = cls.fastapi_demo_app + cls.fastapi_multi_demo_app
cls.fastapi_apps._handle_registry_sync()
lang = (
cls.env["res.lang"]
.with_context(active_test=False)
Expand Down Expand Up @@ -169,3 +173,29 @@ def test_no_commit_on_exception(self) -> None:
expected_message="test",
expected_status_code=status.HTTP_409_CONFLICT,
)

def test_url_matching(self):
# Test the URL mathing method on the endpoint
paths = ["/fastapi", "/fastapi_demo", "/fastapi/v1"]
EndPoint = self.env["fastapi.endpoint"]
self.assertEqual(
EndPoint._find_first_matching_url_path(paths, "/fastapi_demo/test"),
"/fastapi_demo",
)
self.assertEqual(
EndPoint._find_first_matching_url_path(paths, "/fastapi/test"), "/fastapi"
)
self.assertEqual(
EndPoint._find_first_matching_url_path(paths, "/fastapi/v2/test"),
"/fastapi",
)
self.assertEqual(
EndPoint._find_first_matching_url_path(paths, "/fastapi/v1/test"),
"/fastapi/v1",
)

def test_multi_slash(self):
route = "/fastapi/demo-multi/demo/"
response = self.url_open(route, timeout=20)
self.assertEqual(response.status_code, 200)
self.assertIn(self.fastapi_multi_demo_app.root_path, str(response.url))