Regarding the form issue, how to rebuild the form and pass it to the interface endpoint after consuming the stream? #12454
Unanswered
YaoJusheng
asked this question in
Questions
Replies: 1 comment 1 reply
-
|
@YaoJusheng Here's a solution:
Example: class CaptureFormMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
if request.method == "POST" and request.headers.get("content-type", "").startswith("multipart/form-data"):
form = await request.form()
request.state.form = form
form_files = {}
for key, file in form.items():
if isinstance(file, UploadFile):
form_files[key] = await file.read() # Save file content
request.state.form_files = form_files
response = await call_next(request)
return response
@app.post("/upload/")
async def upload_file(request: Request, file: UploadFile = File(...)):
saved_file_content = request.state.form_files.get("file")
return {
"filename": file.filename,
"content": saved_file_content.decode(), # Use cached file content
}Basically, the file gets read once in the middleware and stored, so you can use it later without running into the stream consumption issue that caused the 422 error. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
After each request to upload a file, the interface endpoint always reports an error: 422 Unprocessable Entity, which is caused by the stream being consumed.
So how should I rebuild the formdata in CaptureFormMiddleware to meet the parameter requirements of the endpoint?
Operating System
macOS
Operating System Details
No response
FastAPI Version
0.115.0
Pydantic Version
2.9.2
Python Version
3.10.12
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions