这是我的功能,可以动态创建文件(当用户点击正确的链接时)
@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)
我希望在完成下载后删除文件。我该怎么办?
答案 0 :(得分: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
hook显式关闭文件对象。
答案 1 :(得分:-1)
我已经成功使用了os.unlink一段时间:
import os
os.unlink(os.path.join('/path/files/csv/', '%s' % file))
希望它有所帮助。