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 reading FastAPI request body twice. #1724

Merged
merged 17 commits into from Nov 10, 2022

Conversation

antonpirker
Copy link
Member

@antonpirker antonpirker commented Nov 4, 2022

Starlette/FastAPI is internally caching the request body if read via request.json() or request.body() but NOT when using request.form(). This leads to a problem when our Sentry Starlette integration wants to read the body data and also the users code wants to read the same data.

Solution:
Force caching of request body for .form() calls too, to prevent error when body is read twice.

The tests where mocking .stream() and thus hiding this problem. So the tests have been refactored to mock the underlying ._receive() function instead.

Fixes #1675

@antonpirker antonpirker marked this pull request as draft November 4, 2022 12:59
@antonpirker antonpirker marked this pull request as ready for review November 7, 2022 12:55
@sl0thentr0py sl0thentr0py self-requested a review November 8, 2022 15:29
@vercel
Copy link

vercel bot commented Nov 9, 2022

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated
sentry-python ✅ Ready (Inspect) Visit Preview Nov 10, 2022 at 0:20AM (UTC)

assert form_data.keys() == PARSED_FORM.keys()
assert form_data["username"] == PARSED_FORM["username"]
assert form_data["password"] == PARSED_FORM["password"]
assert form_data["photo"].filename == PARSED_FORM["photo"].filename
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe call await request.stream() or body() right at the end to ensure that there are no regressions? Maybe it'd be relevant to do the same in the rest of tests as well, just to make sure in all cases we still have access to the whole request stream/body?

Copy link
Member

@sl0thentr0py sl0thentr0py left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alright lgtm

@antonpirker antonpirker deleted the antonpirker/1675-fastapi-request-body branch November 10, 2022 12:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

RuntimeError: Stream consumed when reading body with startlette (bug since 1.9.10)
3 participants