Skip to content

A RuntimeError: Stream consumed error is raised when request.body() is read in the custom middleware #2556

Discussion options

You must be logged in to vote

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:

from random import randint

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route


async def read_body_cached(request: Request) -> bytes:
    request.scope['cached_body'] = body = await request.body()
    return body


async def endpoint(request: Request) -> Response

Replies: 1 comment 12 replies

Comment options

You must be logged in to vote
12 replies
@theredfoxlee
Comment options

@ex3cv
Comment options

@theredfoxlee
Comment options

@adriangb
Comment options

Answer selected by Kludex
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
5 participants
Converted from issue

This discussion was converted from issue #2555 on March 29, 2024 14:01.