Skip to content

Commit d7e4758

Browse files
authored
fix: handle Starlette routes in FastAPI middleware (#136)
This commit changes the FastAPI middleware so that the `"route"` info is now optional. If it is not present, the SQL comment will not have the controller/route info. This info is always present in FastAPI routes. However, Starlette-based routes (FastAPI can mount Starlette apps as sub-applications) do not and would crash when the middleware tried to extract the information. Fixes #133
1 parent 14e9442 commit d7e4758

3 files changed

Lines changed: 25 additions & 1 deletion

File tree

python/sqlcommenter-python/google/cloud/sqlcommenter/fastapi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,5 +95,5 @@ def _get_fastapi_route(fastapi_app: FastAPI, scope) -> Optional[Route]:
9595
# and return the route name if found.
9696
match, child_scope = route.matches(scope)
9797
if match == Match.FULL:
98-
return child_scope["route"]
98+
return child_scope.get("route")
9999
return None

python/sqlcommenter-python/tests/fastapi/app.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
from google.cloud.sqlcommenter.fastapi import (
66
SQLCommenterMiddleware, get_fastapi_info,
77
)
8+
from starlette.applications import Starlette
89
from starlette.exceptions import HTTPException as StarletteHTTPException
10+
from starlette.routing import Route
911

1012
app = FastAPI(title="SQLCommenter")
1113

@@ -28,3 +30,15 @@ async def custom_http_exception_handler(request, exc):
2830
status_code=status.HTTP_404_NOT_FOUND,
2931
content=get_fastapi_info(),
3032
)
33+
34+
35+
def starlette_endpoint(_):
36+
return JSONResponse({"from": "starlette"})
37+
38+
39+
starlette_subapi = Starlette(routes=[
40+
Route("/", starlette_endpoint),
41+
])
42+
43+
44+
app.mount("/starlette", starlette_subapi)

python/sqlcommenter-python/tests/fastapi/tests.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,13 @@ def test_get_fastapi_info_in_404_error_context(client):
5252

5353
def test_get_fastapi_info_outside_request_context(client):
5454
assert get_fastapi_info() == {}
55+
56+
57+
def test_get_openapi_does_not_throw_an_error(client):
58+
resp = client.get(app.docs_url)
59+
assert resp.status_code == 200
60+
61+
62+
def test_get_starlette_endpoints_does_not_throw_an_error(client):
63+
resp = client.get("/starlette")
64+
assert resp.status_code == 200

0 commit comments

Comments
 (0)