使用tempfile在flask中创建pdf / xls文档

时间:2015-07-13 18:59:55

标签: python excel pdf flask temporary-files

我想问一下是否可以将PDF / XLS文档创建为临时文件。我这样做后来用烧瓶送他们。对于pdf / xls文件创建,我分别使用 reportlab xlsxwriter 包。当我使用他们的方法保存文档时,我得到“Python临时文件权限被拒绝”错误。当我尝试使用 tempfile 方法关闭时,文件已损坏。有没有办法克服这个问题?或任何其他合适的解决方案?

修改

一些代码段:

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')

与pdf文件类似的故事。

2 个答案:

答案 0 :(得分:2)

使用tempfile.mkstemp()将在磁盘上创建标准临时文件,该文件将一直存在,直到被删除:

import tempfile
import os

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

EDIT tempfile.TemporaryFile()会在关闭后立即销毁,这就是您上面的代码失败的原因。

答案 1 :(得分:0)

您可以通过上下文管理器(或atexit模块)使用和删除 NamedTemporaryFile
示例1:

import os
from tempfile import NamedTemporaryFile

# define class, because everyone loves objects
class 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 something
with 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)})')

输出:

Calling __exit__:
File exists = True
File exists = False

In this point D:\users\fll2cj\AppData\Local\Temp\tmpyv37sp58 does not exist (exists = False)

或者您可以使用 atexit 模块,该模块在程序(cmd)退出时调用已定义的函数。
示例2:

import os, atexit
from tempfile import NamedTemporaryFile

class 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 need
fh = 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.
相关问题