Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Fix parsing for StreamingResponse #225

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 14 additions & 10 deletions slowapi/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,23 +159,27 @@ def __init__(self, app: ASGIApp) -> None:

async def send_wrapper(self, message: Message) -> None:
if message["type"] == "http.response.start":
# do not send the http.response.start message now, so that we can edit the headers
# before sending it, based on what happens in the http.response.body message.
self.initial_message = message

elif message["type"] == "http.response.body":
# Modify the start message immediately instead of storing it
# This allows streaming responses to work correctly by sending
# the start message before any body chunks
if self.error_response:
self.initial_message["status"] = self.error_response.status_code
message["status"] = self.error_response.status_code

if self.inject_headers:
headers = MutableHeaders(raw=self.initial_message["headers"])
headers = MutableHeaders(raw=message["headers"])
headers = self.limiter._inject_asgi_headers(
headers, self.request.state.view_rate_limit
)

# send the http.response.start message just before the http.response.body one,
# now that the headers are updated
await self.send(self.initial_message)
# Send the http.response.start message immediately
# This is crucial for streaming responses which expect
# the start message before any body chunks
self.started = True
await self.send(message)

elif message["type"] == "http.response.body":
# Send body chunks directly without any buffering
# This allows streaming responses to flow naturally
await self.send(message)

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
Expand Down