首页 > 解决方案 > 烧瓶 send_file() 发送空文本文档

问题描述

我正在从数据库中加载一些数据并将其插入到文本文件中,但作为概念证明,我正在使用虚拟数据,但我似乎无法下载包含任何内容的文本文件。

@app.route("/results", methods=["GET"])
def results():
    if request.method == "GET":
        with open("output.txt", 'w') as file:
            file.write("Test 1 2 3")
            return send_file("output.txt", as_attachment=True, cache_timeout=0)

文本文件下载但它是空的?但是,查看创建文件的目录,其中有文本!?

就好像文件在完成写入之前正在下载?

标签: pythonflask

解决方案


打开文件以二进制模式读取对我有用。

尝试将最后一行从

return send_file("output.txt", as_attachment=True, cache_timeout=0)

file_to_be_sent = open("output.txt", 'rb')
return send_file(file_to_be_sent, as_attachment=True, cache_timeout=0)

推荐阅读