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

前端 未结 2 931
情深已故
情深已故 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:33

    I've used os.unlink for a while with success:

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

    Hope it helps.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题