python - 如何即时生成文件并在下载后将其删除?

标签 python flask

这是我的动态创建文件的函数(当用户单击正确的链接时)

@app.route('/survey/<survey_id>/report')
def survey_downloadreport(survey_id):
    survey, bsonobj = survey_get(survey_id) #get object
    resps = response_get_multi(survey_id) #get responses to the object

    fields = ["_id", "sid", "date", "user_ip"] #meta-fields
    fields.extend(survey.formfields) #survey-specific fields

    randname = "".join(random.sample(string.letters + string.digits, 15)) + ".csv" #some random file name

    with open("static//" + randname, "wb") as csvf:
        wr = csv.DictWriter(csvf, fields, encoding = 'cp949')
        wr.writerow(dict(zip(fields, fields))) #dummy, to explain what each column means
        for resp in resps :
            wr.writerow(resp)

    return send_from_directory("static", randname, as_attachment = True)

我希望在完成下载后删除文件。我该怎么做?

最佳答案

在 Linux 上,如果您有一个打开的文件,即使已删除,您仍然可以读取它。这样做:

import tempfile
from flask import send_file

csvf = tempfile.TemporaryFile()
wr = csv.DictWriter(csvf, fields, encoding = 'cp949')
wr.writerow(dict(zip(fields, fields))) #dummy, to explain what each column means
for resp in resps :
    wr.writerow(resp)
wr.close()
csvf.seek(0)  # rewind to the start

send_file(csvf, as_attachment=True, attachment_filename='survey.csv')

csvf文件一创建就删除;一旦文件关闭,操作系统将回收空间(一旦请求完成并且对文件对象的最后引用被删除,cpython 就会为你做)。或者,您可以使用 after_this_request hook显式关闭文件对象。

关于python - 如何即时生成文件并在下载后将其删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14614756/

相关文章:

python - 使用 Flask 无法加载 CSS

python - 如何通过 AJAX 向 Flask 发送数据?

python - (Another) ImportError with Flask under mod_wsgi

python - pytest.mark.parametrize 中的 indirect = True/False 是什么意思?

python - 获取两个提交或分支之间更改文件的列表

python - 重新采样 pandas 数据帧时的 NaN 值

python - Flask 蓝图中的 render_template 使用其他蓝图的模板

python - 在一个 ViewSet 中基于每个对象更改序列化程序?

Python3 运行别名 Bash 命令

python - 在带有 Connexion 的 Python Flask 应用程序中使用哪个记录器