mirror of https://github.com/tiangolo/fastapi.git
When a route uses a custom response class whose __init__ does not expose
a status_code parameter with an int default, and the route decorator
does not specify an explicit status_code, the status_code local variable
in get_openapi_path() was never assigned. This caused an
UnboundLocalError at the point where status_code is used to populate
the operation responses dict.
The bug does not surface with standard Starlette response classes
(JSONResponse, HTMLResponse, PlainTextResponse, StreamingResponse, etc.)
because they all declare status_code: int = 200 (or 307 for redirects)
in their __init__ signatures. It triggers when users define custom
response classes that wrap or omit the status_code parameter, e.g.:
class CustomResponse(Response):
def __init__(self, content, **kwargs):
super().__init__(content=content, status_code=200, **kwargs)
@app.get("/items", response_class=CustomResponse)
async def get_items(): ...
Accessing /openapi.json or /docs would crash with:
UnboundLocalError: cannot access local variable 'status_code'
Fix: initialize status_code = "200" before the conditional block so it
always has a safe default. The existing branches that extract status_code
from the route or from the response class signature still override this
default when applicable.
|
||
|---|---|---|
| .. | ||
| _compat | ||
| dependencies | ||
| middleware | ||
| openapi | ||
| security | ||
| __init__.py | ||
| __main__.py | ||
| applications.py | ||
| background.py | ||
| cli.py | ||
| concurrency.py | ||
| datastructures.py | ||
| encoders.py | ||
| exception_handlers.py | ||
| exceptions.py | ||
| logger.py | ||
| param_functions.py | ||
| params.py | ||
| py.typed | ||
| requests.py | ||
| responses.py | ||
| routing.py | ||
| staticfiles.py | ||
| templating.py | ||
| testclient.py | ||
| types.py | ||
| utils.py | ||
| websockets.py | ||