Flask - 发送字节可下载文件

Flask - send a bytes downloadable file

所以我知道你可以使用 flask 的 send_file 方法在你的计算机上选择一个路径,但在我的例子中,我需要以字节的形式读取文件(因为我从不同的 python-client) 所以我必须将它作为字节发送,然后服务器会收到它。但我需要做一些 URL 会下载你这个文件 我可以只 return 字节它会自动下载文件吗? 所以像这样:

f = b""
with open("/somefile.txt", "rb") as some_file:
    f = some_file.read()

return f # and make this download the file that I read

以下是调整自:https://flask.palletsprojects.com/en/1.1.x/patterns/streaming/
的示例 您需要一个生成数据的生成器函数,然后从 Response 对象调用该函数。

from flask import Response 

@app.route("/")
def index():
    def generate():
        with open('somefile.txt','rb') as f:
            for row in f:
                yield row 
    return Response(generate(), mimetype='text/csv')

然后当你在浏览器中访问这个路由时,会立即提示你下载流数据。