3

我正在尝试启动一个允许用户下载 Word 文档的单页烧瓶应用程序。我已经想出了如何使用 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')
4

4 回答 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')
于 2014-11-20T01:07:24.410 回答
1

您可以在答案中使用send_from_directoryas 。

如果您要发送文本,您也可以使用答案make_response中的帮助程序。

于 2014-11-20T01:07:47.030 回答
0

采用

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

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

于 2018-07-03T17:54:34.610 回答
0

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

参考这两个链接:

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

于 2021-04-03T21:57:13.320 回答