Using tempfile to create pdf/xls documents in flask

10,337

Use tempfile.mkstemp() which will create a standard temp file on disk which will persist until removed:

import tempfile
import os

handle, filepath = tempfile.mkstemp()
f = os.fdopen(handle)  # convert raw handle to file object
...

EDIT tempfile.TemporaryFile() will be destroyed as soon as it's closed, which is why your code above is failing.

Share:
10,337
Rail Suleymanov
Author by

Rail Suleymanov

Updated on June 04, 2022

Comments

  • Rail Suleymanov
    Rail Suleymanov almost 2 years

    I wanted to ask if it's possible to create PDF/XLS documents as temporary files. I'm doing that to send them using flask afterwards. For pdf/xls files creation I use reportlab and xlsxwriter packages respectively. When I save document using their methods, I get the "Python temporary file permission denied" error. When I try to close using the tempfile methods, files become corrupted. Is there any way to overcome this? Or any other suitable solution?

    EDIT:

    Some code snippets:

    import xlswriter
    import tempfile
    from flask import after_this_request
    
    
    @app.route('/some_url', method=['POST'])
    def create_doc_function():
        @after_this_request
        def cleanup(response):
            temp.close()
            return response
    
        temp = tempfile.TemporaryFile()
        book = xlsxwriter.Workbook(temp.name)
        # some actions here ...
        book.close()  # raises "Python temporaty file permission denied" error.
                      # If missed, Excel book is gonna be corrupted, 
                      # i.e. blank, which make sense
        return send_file(temp, as_attachment=True, 
                         attachment_filename='my_document_name.xls')
    

    Similar story with pdf files.