小编Mar*_*kus的帖子

FastAPI:如何通过 API 下载字节

有没有办法通过FastAPI下载文件?我们想要的文件位于 Azure Datalake 中,从数据湖中检索它们不是问题,当我们尝试将从数据湖获取的字节传输到本地计算机时,就会出现问题。

我们尝试过在 FastAPI 中使用不同的模块,例如starlette.responses.FileResponse和 ,fastapi.Response但没有成功。

在 Flask 中这不是问题,可以通过以下方式完成:

from io import BytesIO
from flask import Flask
from werkzeug import FileWrapper

flask_app = Flask(__name__)

@flask_app.route('/downloadfile/<file_name>', methods=['GET'])
def get_the_file(file_name: str):
    the_file = FileWrapper(BytesIO(download_file_from_directory(file_name)))
    if the_file:
        return Response(the_file, mimetype=file_name, direct_passthrough=True)
Run Code Online (Sandbox Code Playgroud)

当使用有效的文件名运行此文件时,文件会自动下载。FastAPI 中有类似的方法吗?

解决了

经过更多的故障排除后,我找到了一种方法来做到这一点。

from fastapi import APIRouter, Response

router = APIRouter()

@router.get('/downloadfile/{file_name}', tags=['getSkynetDL'])
async def get_the_file(file_name: str):
    # the_file object is raw bytes
    the_file = download_file_from_directory(file_name)
    if the_file:
        return Response(the_file)
Run Code Online (Sandbox Code Playgroud)

因此,经过大量的故障排除和数小时的文档查看之后,这就是所需要的一切,只需将字节返回为Response(the_file).

python starlette fastapi

5
推荐指数
1
解决办法
9124
查看次数

标签 统计

fastapi ×1

python ×1

starlette ×1