用 Flask 生成 word 文档?

问题描述 投票:0回答:4

我正在尝试启动一个允许用户下载 word 文档的单页 flask 应用程序。我已经想出如何使用 python-docx 制作/保存文档,但现在我需要使文档在响应中可用。有什么想法吗?

这是我目前所拥有的:

from flask import Flask, render_template
from docx import Document
from cStringIO import StringIO

@app.route('/')
def index():
    document = Document()
    document.add_heading("Sample Press Release", 0)
    f = StringIO()
    document.save(f)
    length = f.tell()
    f.seek(0)
    return render_template('index.html')
python flask python-docx
4个回答
5
投票

代替

render_template('index.html')
你可以:

from flask import Flask, render_template, send_file
from docx import Document
from cStringIO import StringIO

@app.route('/')
def index():
    document = Document()
    document.add_heading("Sample Press Release", 0)
    f = StringIO()
    document.save(f)
    length = f.tell()
    f.seek(0)
    return send_file(f, as_attachment=True, attachment_filename='report.doc')

1
投票

您可以像

this
答案一样使用send_from_directory

如果您要发送文本,您也可以使用

make_response
助手,如this answer.


1
投票

对于那些在我之后经过的人...

参考这两个链接:

io.StringIO
现在取代
cStringIO.StringIO

它也会引发错误 因为

document.save(f)
应该收到通行证或二进制文件

代码应该是这样的:

from flask import Flask, render_template, send_file
from docx import Document
from io import BytesIO

@app.route('/')
def index():
    document = Document()
    f = BytesIO()
    # do staff with document
    document.save(f)
    f.seek(0)

    return send_file(
        f,
        as_attachment=True,
        attachment_filename='report.docx'
    )


0
投票

使用

return Response(generate(), mimetype='text/docx')

Generate() 在您的情况下应替换为 f 有关更多信息,请查看在烧瓶中流式传输 http://flask.pocoo.org/docs/1.0/patterns/streaming/

© www.soinside.com 2019 - 2024. All rights reserved.