【发布时间】:2018-06-25 13:08:25
【问题描述】:
我有一个 Python Flask 应用程序,它获取从远程 FTP 服务器下载文件的请求。我使用BytesIO 来保存使用retrbinary 从FTP 服务器下载的文件的内容:
import os
from flask import Flask, request, send_file
from ftplib import FTP
from io import BytesIO
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/download_content', methods=['GET'])
def download_content():
filepath = request.args.get("filepath").strip()
f = FTP(my_server)
f.login(my_username, my_password)
b = BytesIO()
f.retrbinary("RETR " + filepath, b.write)
b.seek(0)
return send_file(b, attachment_filename=os.path.basename(filepath))
app.run("localhost", port=8080)
这里的问题是,当download_content路由被命中时,文件的内容首先进入BytesIO对象,然后发送到前端进行下载。
在从 FTP 服务器下载文件时,如何将文件流式传输到前端?我迫不及待地等待文件完全下载到 BytesIO 对象中,然后执行 send_file,因为这可能既是内存效率低下的,也是更耗时的。
我已经读过 Flask 的 send_file 接受 generator 对象,但我怎样才能将 BytesIO 对象 yield 以块的形式变为 send_file?
【问题讨论】: