代码之家  ›  专栏  ›  技术社区  ›  Kleyson Rios

如何在“return FileResponse(文件路径)”之后删除文件`

  •  0
  • Kleyson Rios  · 技术社区  · 4 年前

    我正在使用FastAPI接收一个图像,对其进行处理,然后将图像作为文件响应返回。

    但是返回的文件是一个临时文件,需要在端点返回后删除。

    @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)
    
    

    返回文件后如何删除?

    0 回复  |  直到 4 年前
        1
  •  8
  •   alex_noname    4 年前

    您可以在文件中删除文件 background task ,因为它将运行 之后 响应已发送。

    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)
    

    dependency with yield . 这个 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() 返回包含文件描述符和路径的元组。

        2
  •  -1
  •   Yagiz Degirmenci    4 年前

    返回 StreamingResponse 在您的情况下,这将是一个更好的选择,而且内存效率更高,因为文件操作将阻止事件循环的整个执行。

    b64encoded 流线型响应 从那开始。

    from fastapi.responses import StreamingResponse
    from io import BytesIO
    
    @app.post("/send")
    async def send(imagem_base64: str = Form(...)):
        in_memory_file = BytesIO()
        image = base64_to_image(imagem_base64)
        image.save(in_memory_file, dpi=(600, 600), format='JPEG', subsampling=0, quality=85)
        in_memory_file.seek(0)
        return StreamingResponse(in_memory_file.read(), media_type="image/jpeg")
    
    推荐文章