我正在尝试启动一个允许用户下载 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')
代替
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')
对于那些在我之后经过的人...
参考这两个链接:
现在取代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'
)
使用
return Response(generate(), mimetype='text/docx')
Generate() 在您的情况下应替换为 f 有关更多信息,请查看在烧瓶中流式传输 http://flask.pocoo.org/docs/1.0/patterns/streaming/