本文介绍了使用tempfile在烧瓶中创建pdf / xls文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

编辑

一些代码片段: / p>

 导入xlswriter 
导入tempfile $ b $从瓶子导入after_this_request


@ app.route('/ some_url',method = ['POST'])
def create_doc_function():
@ after_this_request
def cleanup(response):
temp。 close()
返回响应

temp = tempfile.TemporaryFile()
book = xlsxwriter.Workbook(temp.name)
# b $ b book.close()#引发Python节奏文件权限被拒绝错误。
#如果错过,Excel书籍将被损坏,
#ie空白,这是有道理的
返回send_file(temp,as_attachment = True,
attachment_filename ='my_document_name.xls' )

与pdf文件类似的故事

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

b
$ b pre $ 进口临时文件
进口os

句柄,filepath = tempfile.mkstemp()
f = os .fdopen(handle)#将原始句柄转换为文件对象
...

编辑
tempfile.TemporaryFile()会在关闭时被销毁,这就是为什么你的代码失败了。


I wanted to ask if it's possible to create PDF/XLS documents as temporary files. I'm doing that to send them using flask afterwards. For pdf/xls files creation I use reportlab and xlsxwriter packages respectively. When I save document using their methods, I get the "Python temporary file permission denied" error. When I try to close using the tempfile methods, files become corrupted. Is there any way to overcome this? Or any other suitable solution?

EDIT:

Some code snippets:

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

Similar story with pdf files.

解决方案

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

import tempfile
import os

handle, 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.

这篇关于使用tempfile在烧瓶中创建pdf / xls文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 05:49