Reading file into background task #11177
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, BackgroundTasks, File, UploadFile
from typing import Optional
import os
app = FastAPI()
async def print_file_content(file: UploadFile):
file_d = await file.read()
print("hello")
@app.post("/upload/")
async def upload_file(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
background_tasks.add_task(print_file_content, file) Description
Operating SystemLinux, macOS Operating System DetailsNo response FastAPI Version0.109.2 Pydantic Version2.5.3 Python Version3.8.6 Additional ContextThe Error is : |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hi @zekrismh. The error is being raised because the UploadFile object is being closed once you pass it to the background task. The ideal solution should be read the file within the same endpoint context and pass its content. Here's an example from fastapi import FastAPI, BackgroundTasks, File, UploadFile
from typing import Optional
import os
app = FastAPI()
async def get_file_content(file: UploadFile):
return await file.read()
async def print_file_content(file_content: bytes):
print(file_content)
# Process the file content here
@app.post("/upload/")
async def upload_file(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
file_content = await get_file_content(file)
background_tasks.add_task(print_file_content, file_content)
return {"message": "File uploaded successfully"} Another solution, if the file is too big and need to be read to do any other complex logic, You should save it in disk and then read it from the background task from the disk or storage you want. UploadFile is closing automatically the objects when you pass it to background task to avoid leave opened files. It was a recent changed to avoid performance issues, that's the reason it was working in and old fastapi version |
Beta Was this translation helpful? Give feedback.
Hi @zekrismh.
The error is being raised because the UploadFile object is being closed once you pass it to the background task.
The ideal solution should be read the file within the same endpoint context and pass its content.
Here's an example