question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

"request.json()" hangs indefinitely in middleware

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI, Request, Response
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint


class Middleware(BaseHTTPMiddleware):

    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
        await request.json()
        response = await call_next(request)
        return response


app = FastAPI()
app.add_middleware(Middleware)


@app.post("/test")
async def test(test: dict) -> dict:
    return {"data": "test"}

Description

  • Run script with: uvicorn main:app --reload
  • Run CURL with POST request: curl -X 'POST' 'http://localhost:8000/test' -H 'accept: application/json' -H 'Content-Type: application/json' -d '{"test": "test"}'

The application keeps hanging indefinitely and don’t send a response to the request. I tested the equivalent code using app = Starlette() and it answers correctly.

Operating System

Linux

Operating System Details

Ubuntu 22.04

FastAPI Version

0.79.0

Python Version

Python 3.10.4

Additional Context

No response

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:11 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
XingDongZhecommented, Oct 5, 2022

@araujo88 It can’t be using self.stream(), for per request, only one time can use self.stream().
Or you will hang forever because of await self.event_message.wait()
You can see here: uvicorn/protocols/http/h11_impl.py#L543
This is because that when self.stream() done, there are no action to notify self.event_message This asyncio.Event will be notified of four actions:

  • when Connection Lost
  • when body_data received
  • when body_data readed done
  • when write reponse data done

And you can try this:

async for chunk in request.stream():
    print(chunk)
await request.json()
1reaction
csrgxtucommented, Sep 15, 2022

@araujo88 you can ref this issue: https://github.com/tiangolo/fastapi/issues/394

in summary it is a bug or design issue from starlette, and there is work around:

from typing import Mapping

from starlette.requests import Request

from fastapi import FastAPI, APIRouter, Depends

app = FastAPI()
api_router = APIRouter()

@api_router.post("/")
def read_root(arg: Mapping[str, str]):
    return {"Hello": "World"}

async def auth_middleware(request: Request):
    # you can implement your auth here
    print(await request.json())

# the trick here is including auth_middleware in the dependencies:
app.include_router(api_router, dependencies=[Depends(auth_middleware)])

thus this middleware logic will work on every requests, we use it same way in our production env, works fine.

note: Dependencies will inject your auth logic into each request, for more detail ref: https://fastapi.tiangolo.com/tutorial/dependencies/

Read more comments on GitHub >

github_iconTop Results From Across the Web

Middleware Request parse Hangs forever · Issue #847 - GitHub
The problem I am seeing is that this triggers the request to hang forever. The following is how you can reproduce it. app...
Read more >
Why does fastapi hang when adding a middleware to print the ...
json() is allowed only once in request life-cycle in API, and BaseHTTPMiddleware also creates a Request object on its own (which causes hanging...
Read more >
Supporting Promises in Express Middleware - Mastering JS
Express doesn't support promises or async/await in middleware or routes. ... toString(); // Request will hang forever because `res.json()` ...
Read more >
Request stuck on pending : r/node - Reddit
Here is my request code from React: ... Try add res.end() after the JSON output, that could end the ... Cors middleware is...
Read more >
Supporting integration tests with WebApplicationFactory in ...
It's an edge case, but without it, the test could hang indefinitely. The DeferredHost is responsible for waiting for the application to properly ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found