简体   繁体   English

如何动态生成文件并在下载后删除?

[英]How can I generate file on the fly and delete it after download?

here's my function that creates file on the fly(when the user clicks proper link) 这是我的功能,即动创建文件(当用户点击正确的链接时)

@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)

I'd like to have file to be deleted after completing of the download. 我想在完成下载后删除文件。 How can I do it? 我该怎么做?

On Linux, if you have an open file you can still read it even when deleted. 在Linux上,如果您有一个打开的文件,即使删除它也仍然可以读取它。 Do this: 做这个:

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')

The csvf file is deleted as soon as it is created; csvf文件一旦创建就会被删除; the OS will reclaim the space once the file is closed (which cpython will do for you as soon as the request is completed and the last reference to the file object is deleted). 一旦文件关闭,操作系统将回收空间(一旦请求完成并且删除了对文件对象的最后一个引用,cpython将为您完成)。 Optionally, you could use the after_this_request hook to explicitly close the file object. (可选)您可以使用after_this_request挂钩显式关闭文件对象。

I've used os.unlink for a while with success: 我已经成功地使用了os.unlink一段时间了:

import os

os.unlink(os.path.join('/path/files/csv/', '%s' % file))

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM