Python 使用Flask生成word文档?

Python 使用Flask生成word文档?,python,flask,python-docx,Python,Flask,Python Docx,我正在尝试开发一个单页flask应用程序,允许用户下载word文档。我已经知道了如何使用pythondocx制作/保存文档,但是现在我需要在响应中提供文档。有什么想法吗 以下是我目前掌握的情况: from flask import Flask, render_template from docx import Document from cStringIO import StringIO @app.route('/') def index(): document = Document(

我正在尝试开发一个单页flask应用程序,允许用户下载word文档。我已经知道了如何使用pythondocx制作/保存文档,但是现在我需要在响应中提供文档。有什么想法吗

以下是我目前掌握的情况:

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

除了
render\u模板('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')

您可以使用
send\u from\u目录
作为答案

如果您正在发送文本,您也可以在应答中使用
make_response
帮助程序。

使用

return Response(generate(), mimetype='text/docx')
在您的情况下,Generate()应该替换为f 有关更多信息,请参阅烧瓶中的流
对于那些在我之后经过的人…

关于这两个环节:

  • [问题]
  • [GitHub问题]
io.StringIO
现在取代了
cStringIO.StringIO

它还会引发一个错误 as
document.save(f)
应接收一个pass或二进制文件

代码应该是这样的:

从flask导入flask,呈现\u模板,发送\u文件
从docx导入文档
从io导入字节io
@应用程序路径(“/”)
def index():
文件=文件()
f=字节()
#向员工提供文件
文件保存(f)
f、 搜索(0)
返回发送文件(
F
如附件=真,
附件_filename='report.docx'
)

这是最简单的方法,因此我将此方法标记为答案。感谢它对我的帮助!