使用Flask生成word文档?

Bar*_*Bar 2 python flask python-docx

我正在尝试启动单页烧瓶应用程序,允许用户下载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')
Run Code Online (Sandbox Code Playgroud)

Doo*_*beh 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')
Run Code Online (Sandbox Code Playgroud)