【发布时间】:2015-10-02 04:31:02
【问题描述】:
我想问是否可以将 PDF/XLS 文档创建为临时文件。我这样做是为了之后使用烧瓶发送它们。对于 pdf/xls 文件的创建,我分别使用 reportlab 和 xlsxwriter 包。当我使用他们的方法保存文档时,我收到“Python 临时文件权限被拒绝”错误。当我尝试使用 tempfile 方法关闭时,文件已损坏。有什么办法可以克服这个吗?还是有其他合适的解决方案?
编辑:
一些代码sn-ps:
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 文件的类似故事。
【问题讨论】:
-
你能发布一个你到目前为止的代码示例吗?
-
@matthewatabet,当然。检查更新的帖子。
-
谢谢!我在下面使用持久临时文件的答案应该可以解决问题。
标签: python excel pdf flask temporary-files