gpt4 book ai didi

python - 使用 tempfile 在 Flask 中创建 pdf/xls 文档

转载 作者:行者123 更新时间:2023-12-01 04:37:58 26 4
gpt4 key购买 nike

我想问是否可以将 PDF/XLS 文档创建为临时文件。我这样做是为了之后使用 flask 发送它们。对于 pdf/xls 文件创建,我分别使用 reportlabxlsxwriter 软件包。当我使用他们的方法保存文档时,出现“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 文件类似的故事。

最佳答案

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

import tempfile
import os

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

编辑tempfile.TemporaryFile() 一旦关闭就会被销毁,这就是上面的代码失败的原因。

关于python - 使用 tempfile 在 Flask 中创建 pdf/xls 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31391344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com