我使用FastAPI接收图像,对其进行处理,然后将图像作为FileResponse返回。
但是返回的文件是一个临时文件,需要在端点返回它之后删除它。
@app.post("/send")
async def send(imagem_base64: str = Form(...)):
# Convert to a Pillow image
image = base64_to_image(imagem_base64)
temp_file = tempfile.mkstemp(suffix = '.jpeg')
image.save(temp_file, dpi=(600, 600), format='JPEG', subsampling=0, quality=85)
return FileResponse(temp_file)
# I need to remove my file after return it
os.remove(temp_file)如何在文件返回后删除它?
发布于 2020-11-06 15:10:23
您可以删除背景任务中的文件,因为它将在发送响应后运行。
import os
import tempfile
from fastapi import FastAPI
from fastapi.responses import FileResponse
from starlette.background import BackgroundTasks
app = FastAPI()
def remove_file(path: str) -> None:
os.unlink(path)
@app.post("/send")
async def send(background_tasks: BackgroundTasks):
fd, path = tempfile.mkstemp(suffix='.txt')
with os.fdopen(fd, 'w') as f:
f.write('TEST\n')
background_tasks.add_task(remove_file, path)
return FileResponse(path)另一种方法是使用依赖与产量。finally块代码将在发送响应后执行,甚至在所有后台任务完成之后也会执行。
import os
import tempfile
from fastapi import FastAPI, Depends
from fastapi.responses import FileResponse
app = FastAPI()
def create_temp_file():
fd, path = tempfile.mkstemp(suffix='.txt')
with os.fdopen(fd, 'w') as f:
f.write('TEST\n')
try:
yield path
finally:
os.unlink(path)
@app.post("/send")
async def send(file_path=Depends(create_temp_file)):
return FileResponse(file_path)注意:mkstemp()返回一个带有文件描述符和路径的元组。
发布于 2021-07-29 16:16:34
可以将清理任务作为FileResponse的参数传递。
from starlette.background import BackgroundTask
# ...
def cleanup():
os.remove(temp_file)
return FileResponse(
temp_file,
background=BackgroundTask(cleanup),
)更新12-08-2022
如果有人动态地生成文件名,则可以将参数传递给后台任务,例如:
return FileResponse(
temp_file,
background=BackgroundTask(cleanup, file_path),
)然后,需要调整cleanup函数以接受一个参数,该参数将是文件名,并以文件名作为参数而不是全局变量调用os.remove函数。
发布于 2021-10-27 13:51:24
建议发送带有删除文件或文件夹的后台任务的FileResponse。
单击此处获取更多信息
后台任务将在响应服务之后运行,因此它可以安全地删除文件/文件夹。
# ... other important imports
from starlette.background import BackgroundTasks
@app.post("/send")
async def send(imagem_base64: str = Form(...), bg_tasks: BackgroundTasks):
# Convert to a Pillow image
image = base64_to_image(imagem_base64)
temp_file = tempfile.mkstemp(suffix = '.jpeg')
image.save(temp_file, dpi=(600, 600), format='JPEG', subsampling=0, quality=85)
bg_tasks.add_task(os.remove, temp_file)
return FileResponse(
temp_file,
background=bg_tasks
) https://stackoverflow.com/questions/64716495
复制相似问题