如何解决FastAPI:如何通过API下载字节
是否可以通过FastAPI下载文件?我们想要的文件位于Azure Datalake中,从湖中检索它们不是问题,当我们尝试将从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)
使用有效的文件名运行该文件时,文件会自动下载。在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)
即可,而无需额外的参数,也无需为原始字节对象设置任何格式。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。