Describe the bug
Response from the server is never received in case of using middleware.
To Reproduce
Steps to reproduce the behavior:
$ cat main.py
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Entry point of the application."""
import logging
from fastapi import Depends, FastAPI, HTTPException
from pydantic import BaseModel
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
logger = logging.getLogger(__name__)
class AuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = Response("Faled to authenticate", status_code=401)
try:
json = await request.json()
request.state.is_authenticated = True
logger.info(f"request.body: {json} ")
response = await call_next(request)
finally:
request.state.is_authenticated = False
return response
app = FastAPI(title="Nice Server",
description="This is a very fancy project, with auto docs for the API and everything",
version="0.1.0",
docs_url="/docs", redoc_url=None)
app.add_middleware(AuthMiddleware)
class SomeTimestamp(BaseModel):
ts: int
async def is_authenticated(request: Request):
return request.state.is_authenticated
@app.post("/latest", response_model=SomeTimestamp, summary="Returning the latest ")
async def latest(*, some_timestamp: SomeTimestamp, is_authenticated: bool = Depends(is_authenticated)):
logger.info(f"Let's see if this is authenticated: {is_authenticated}")
if not is_authenticated:
raise HTTPException(status_code=401, detail="Failed to verify the incoming token")
logger.info(f"Received for prediction {some_timestamp.ts}")
return some_timestamp.ts
Now run the server:
uvicorn main_server:app --reload
Now query this using curl:
curl --header "Content-Type: application/json" \
--request POST \
--data '{"ts":"123123"}' \
http://127.0.0.1:8000/latest
Expected behavior
The server is stuck before sending response.
Screenshots
If applicable, add screenshots to help explain your problem.
Environment:
import fastapi
print(fastapi.__version__)
0.18.0
python --version
3.7
Additional context
Add any other context about the problem here.
Similar bug is encountered by @yihuang as well. Just the difference being accessing the json from the request body.
I wasn't sure earlier if this was an implementation issue on my side, but it seems this is happening in the form object as well.
@tiangolo any input would be much appreciated, thanks.
Reference issue:
https://github.com/tiangolo/fastapi/issues/191
I think this is a starlette problem(https://github.com/encode/starlette/issues/495).
Closing this here as it is already being reported/tracked in starlette https://github.com/encode/starlette/issues/493
Thanks for the report @ansrivas , and thanks for the help here @yihuang and @gwdekker .
Yep, it seems it's a problem upstream in Starlette. Let's see if it can be solved there directly first.