[Bug/Question] Response from the server is never received in case of using middleware.
See original GitHub issueDescribe 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:
- OS: [ Linux]
- FastAPI Version [e.g. 0.18.0], get it with:
import fastapi
print(fastapi.__version__)
0.18.0
- Python version, get it with:
python --version
3.7
Additional context Add any other context about the problem here.
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (2 by maintainers)
Top Results From Across the Web
Making and Using HTTP Middleware - Alex Edwards
Build up a chain of handlers containing both our middleware handler and our normal application handler, which we can register with a router....
Read more >What is middleware? - Red Hat
Middleware is software that provides common services and capabilities to applications outside of what's offered by the operating system.
Read more >Using middleware - Express.js
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function....
Read more >How Node JS middleware Works? - Selvaganesh - Medium
A middleware is basically a function that will the receive the Request and Response objects, just like your route Handlers do. As a...
Read more >Middleware - FastAPI
And also with every response before returning it. It takes each request that comes to ... A function call_next that will receive the...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
See also https://github.com/encode/starlette/issues/493
I think this is a starlette problem(https://github.com/encode/starlette/issues/495).