"receive" in middleware doesn't work #2864
Answered
by
dmitrykaramin
dmitrykaramin
asked this question in
Potential Issue
-
starlette 0.45.3 Using middleware from documentation
doesn't work as "receive" (receive_logging_request_body_size) never called during request.
|
Beta Was this translation helpful? Give feedback.
Answered by
dmitrykaramin
Feb 7, 2025
Replies: 1 comment 5 replies
-
Did you send an actual request with data? from fastapi import FastAPI
from fastapi.middleware import Middleware
from fastapi.testclient import TestClient
from pydantic import BaseModel
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class LoggedRequestBodySizeMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope['type'] != 'http':
await self.app(scope, receive, send)
return
body_size = 0
async def receive_logging_request_body_size() -> Message:
nonlocal body_size
message = await receive()
assert message['type'] == 'http.request'
body_size += len(message.get('body', b''))
if not message.get('more_body', False):
print(f'Size of request body was: {body_size} bytes')
return message
await self.app(scope, receive_logging_request_body_size, send)
app = FastAPI(middleware=[Middleware(LoggedRequestBodySizeMiddleware)])
class Salute(BaseModel):
name: str
class SaluteResponse(BaseModel):
message: str
@app.post('/echo')
async def upload(salute: Salute) -> SaluteResponse:
return SaluteResponse(message=f'Hello {salute.name}')
client = TestClient(app)
response = client.post('/echo', json={'name': 'World'})
assert response.status_code == 200, response.text
|
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My experiments show than presence of scheme in method arguments makes logic execute "receive" method
even if there is no data in body
Size of request body was: 0 bytes