【问题标题】:FastAPI: How to download bytes through the APIFastAPI:如何通过 API 下载字节
【发布时间】:2020-09-14 12:14:38
【问题描述】:

有没有办法通过 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)

【问题讨论】:

  • 您应该把它作为答案放在下面并将其标记为正确答案以关闭此问题。

标签: python flask fastapi starlette


【解决方案1】:

据我所知,您需要将media_type 设置为适当的类型。一年前我用一些代码做到了这一点,并且效果很好。

@app.get("/img/{name}")
def read(name: str, access_token_cookie: str=Cookie(None)):
  r = internal.get_data(name)
  if r is None:
    return RedirectResponse(url="/static/default.png")
  else:
    return Response(content=r["data"], media_type=r["mime"])

r 是一个字典,data 是原始字节,mime 是 PythonMagick 给出的数据类型。

【讨论】:

    【解决方案2】:

    在进行了更多故障排除后,我找到了一种方法。

    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),没有额外的参数,也没有对原始字节对象进行额外的格式化。

    【讨论】:

      猜你喜欢
      • 2022-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 2019-10-06
      • 2020-07-06
      • 2011-02-24
      相关资源
      最近更新 更多