使用tempfile在烧瓶中创buildpdf / xls文档

我想问问是否可以创buildPDF / XLS文档作为临时文件。 我正在这样做后来用烧瓶送他们。 对于pdf / xls文件的创build,我分别使用reportlabxlsxwriter软件包。 当我用他们的方法保存文档时,我得到了“Python临时文件权限被拒绝”的错误。 当我尝试closures使用tempfile方法时,文件被损坏。 有什么办法可以克服吗? 还是其他合适的解决scheme?

编辑:

一些代码片段:

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, # ie blank, which make sense return send_file(temp, as_attachment=True, attachment_filename='my_document_name.xls') 

与pdf文件类似的故事。

使用tempfile.mkstemp()将会在磁盘上创build一个标准的临时文件,这个文件将一直保留直到被删除:

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

编辑tempfile.TemporaryFile()将被closures,这就是为什么你的代码失败。