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

前端 未结 2 930
情深已故
情深已故 2021-01-18 08:17

here\'s my function that creates file on the fly(when the user clicks proper link)

@app.route(\'/survey//report\')
def survey_downloadreport         


        
2条回答
  •  一整个雨季
    2021-01-18 08:43

    On Linux, if you have an open file you can still read it even when deleted. 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; 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). Optionally, you could use the after_this_request hook to explicitly close the file object.

提交回复
热议问题