python - FastAPI:如何通过 API 下载字节

标签 python flask fastapi starlette

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

我们尝试在 FastAPI 中使用不同的模块,例如 starlette.responses.FileResponsefastapi.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)

当使用有效的文件名运行时,文件会自动下载。 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)

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

最佳答案

在进行更多故障排除后,我找到了执行此操作的方法。

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)

因此,经过大量的故障排除和数小时的文档查看后,这就是全部,只需将字节作为 Response(the_file) 返回,没有额外的参数,也没有原始字节的额外格式对象。

关于python - FastAPI:如何通过 API 下载字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63884139/

相关文章:

python - 我的项目 forms.py 文件出现错误

html - 将HTML标记嵌入Flask WTForms字段中

flask - 从 Docker 容器公开 WSGI 应用程序

python-3.x - FastAPI + Tortoise ORM 出现 KeyError : '__module__' on pydantic_model_creator

Python。要求用户输入文件名

python - gimp python - 如何更改像素颜色?

python - 如何连接到 sqlite3 db 文件并在 fastapi 中获取内容?

nginx - 带有 nginx 的 FastAPI 不提供 HTTPS 中的静态文件

python - 如何在不使用 matplotlib 的情况下使用不同类型的图(条形图和线条图)绘制不同的列(仅使用 pandas)

python - 如何使虚拟机中运行的flask服务器对外可用?