Using tempfile to create pdf/xls documents in flask Using tempfile to create pdf/xls documents in flask flask flask

Using tempfile to create pdf/xls documents in flask


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

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

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


You can use and delete NamedTemporaryFile with context manager (or atexit module). It may do the dirty job for you.
Example 1:

import osfrom tempfile import NamedTemporaryFile# define class, because everyone loves objectsclass FileHandler():    def __init__(self):        '''        Let's create temporary file in constructor        Notice that there is no param (delete=True is not necessary)         '''        self.file = NamedTemporaryFile()    # write something funny into file...or do whatever you need    def write_into(self, btext):        self.file.write(btext)    def __enter__(self):        '''        Define simple but mandatory __enter__ function - context manager will require it.        Just return the instance, nothing more is requested.        '''        return self    def __exit__(self, exc_type, exc_val, exc_tb):        '''        Also define mandatory __exit__ method which is called at the end.        NamedTemporaryFile is deleted as soon as is closed (function checks it before and after close())        '''        print('Calling __exit__:')        print(f'File exists = {os.path.exists(self.file.name)}')        self.file.close()        print(f'File exists = {os.path.exists(self.file.name)}')# use context mamager 'with' to create new instance and do somethingwith FileHandler() as fh:    fh.write_into(b'Hi happy developer!')print(f'\nIn this point {fh.file.name} does not exist (exists = {os.path.exists(fh.file.name)})')

Output:

Calling __exit__:File exists = TrueFile exists = FalseIn this point D:\users\fll2cj\AppData\Local\Temp\tmpyv37sp58 does not exist (exists = False)

Or you can use atexit module which calls defined function when program (cmd) exits.
Example 2:

import os, atexitfrom tempfile import NamedTemporaryFileclass FileHandler():    def __init__(self):        self.file = NamedTemporaryFile()        # register function called when quit        atexit.register(self._cleanup)    def write_into(self, btext):        self.file.write(btext)    def _cleanup(self):        # because self.file has been created without delete=False, closing the file causes its deletion         self.file.close()# create new instance and do whatever you needfh = FileHandler()fh.write_into(b'Hi happy developer!')# now the file still exists, but when program quits, _cleanup() is called and file closed and automaticaly deleted.