Browse Source

fix: replace assert with raise FastAPIError in routing.py

Three `assert isinstance(...)` guards in routing.py are used as runtime
checks for required ASGI scope keys (fastapi_middleware_astack,
fastapi_inner_astack). Under `python -O`, all assert statements are
stripped, converting these diagnostic guards into silent AttributeError
exceptions with no context.

Replace with explicit `if not isinstance(...): raise FastAPIError(...)`
to preserve the error messages regardless of Python optimization level.

Affects:
- get_request_handler() HTTP middleware stack check (line 349)
- get_request_handler() HTTP dependency stack check (line 418)
- get_websocket_app() WebSocket dependency stack check (line 514)
pull/14995/head
Matt Hartigan 5 months ago
parent
commit
dec8c81319
  1. 9
      fastapi/routing.py

9
fastapi/routing.py

@ -346,7 +346,8 @@ def get_request_handler(
async def app(request: Request) -> Response:
response: Response | None = None
file_stack = request.scope.get("fastapi_middleware_astack")
assert isinstance(file_stack, AsyncExitStack), (
if not isinstance(file_stack, AsyncExitStack):
raise FastAPIError(
"fastapi_middleware_astack not found in request scope"
)
@ -415,7 +416,8 @@ def get_request_handler(
# Solve dependencies and run path operation function, auto-closing dependencies
errors: list[Any] = []
async_exit_stack = request.scope.get("fastapi_inner_astack")
assert isinstance(async_exit_stack, AsyncExitStack), (
if not isinstance(async_exit_stack, AsyncExitStack):
raise FastAPIError(
"fastapi_inner_astack not found in request scope"
)
solved_result = await solve_dependencies(
@ -511,7 +513,8 @@ def get_websocket_app(
mount_path = websocket.scope.get("root_path", "").rstrip("/")
endpoint_ctx["path"] = f"WS {mount_path}{dependant.path}"
async_exit_stack = websocket.scope.get("fastapi_inner_astack")
assert isinstance(async_exit_stack, AsyncExitStack), (
if not isinstance(async_exit_stack, AsyncExitStack):
raise FastAPIError(
"fastapi_inner_astack not found in request scope"
)
solved_result = await solve_dependencies(

Loading…
Cancel
Save