7

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

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

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

4

2 回答 2

7

在 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挂钩显式关闭文件对象。

于 2013-01-30T22:17:57.380 回答
-1

我已经成功使用了 os.unlink 一段时间:

import os

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

希望能帮助到你。

于 2013-01-30T22:19:21.780 回答