【问题标题】:Generating word docs with Flask?用 Flask 生成 word 文档?
【发布时间】:2015-01-17 17:51:06
【问题描述】:

我正在尝试启动一个允许用户下载 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')

【问题讨论】:

    标签: python flask python-docx


    【解决方案1】:

    你可以用 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')
    

    【讨论】:

    • 这是最简单的方法,所以我将其标记为答案。
    • 感谢它对我帮助很大!
    【解决方案2】:

    您可以像this 答案一样使用send_from_directory

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

    【讨论】:

      【解决方案3】:

      使用

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

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

      【讨论】:

        【解决方案4】:

        对于那些追随我的人......

        参考这两个链接:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-26
          • 1970-01-01
          • 1970-01-01
          • 2011-03-14
          • 1970-01-01
          • 1970-01-01
          • 2010-11-01
          • 2020-05-02
          相关资源
          最近更新 更多