A RuntimeError: Stream consumed
error is raised when request.body()
is read in the custom middleware
#2556
Answered
by
adriangb
theredfoxlee
asked this question in
Potential Issue
-
Hi, I encountered the following issue while using Starlette today :) Issue descriptionA How to reproduce the issue?Codefrom starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware import Middleware
async def testpage(request):
await request.body()
return JSONResponse({'hello': 'world'})
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
await request.body() # THIS WILL RAISE -> RuntimeError: Stream consumed
return response
app = Starlette(
debug=True,
routes=[Route('/', testpage, methods=["PUT"])],
middleware=[Middleware(CustomMiddleware)]
) Dependenciesstarlette==0.37.2
uvicorn==0.29.0 Commands
Known workarounds
This is my first time using |
Beta Was this translation helpful? Give feedback.
Answered by
adriangb
Aug 13, 2024
Replies: 1 comment 12 replies
-
I believe it's a bug. May I move it to the issues? |
Beta Was this translation helpful? Give feedback.
12 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This isn't a bug, this is just how things work with ASGI / streaming data.
If you don't want to first read (and thus cache) the request body in the middleware I recommend you do something like this: