Using tempfile to create pdf/xls documents in flask

偶尔善良 提交于 2019-12-04 02:21:44

问题


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.


回答1:


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

EDIT tempfile.TemporaryFile() will be destroyed as soon as it's closed, which is why your code above is failing.



来源:https://stackoverflow.com/questions/31391344/using-tempfile-to-create-pdf-xls-documents-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!