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ファイルは作成されるとすぐに削除されます。ファイルが閉じられると、OSはスペースを再利用します(リクエストが完了し、ファイルオブジェクトへの最後の参照が削除されるとすぐに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 に答える