【问题标题】:Return a download and rendered page in one Flask response在一个 Flask 响应中返回下载和渲染页面
【发布时间】:2016-03-04 18:15:06
【问题描述】:

我想返回一个呈现的页面和一个可下载的文件作为对请求的响应。我试图返回两个响应的元组,但它不起作用。如何提供下载和页面?

return response, render_template('database.html')
return render_template('database.html'), response

Flask 是否能够处理这种情况?似乎是一个司空见惯的问题,我只是想发回一个文件以供下载,然后渲染页面。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    您不能对单个请求返回多个响应。相反,生成文件并将其存储在某处,然后 serve them 使用另一条路线。返回您渲染的模板,其中包含用于提供文件的路由的 url。

    @app.route('/database')
    def database():
        # generate some file name
        # save the file in the `database_reports` folder used below
        return render_template('database.html', filename=stored_file_name)
    
    @app.route('/database_download/<filename>')
    def database_download(filename):
        return send_from_directory('database_reports', filename)
    

    在模板中,使用url_for生成下载url。

    <a href="{{ url_for('database_download', filename=filename) }}">Download</a>
    

    【讨论】:

      【解决方案2】:

      我只是在寻找更简单的东西,所以这里为那些寻找更简单的东西的人提供了解决方案:

      一个非常简单而肮脏的解决方案是使用 javascript。

      例如这样:

      <button onclick="goBack()"><a href="{{ url_for('export') }}">Export</a></button>
      
      <script>
      function goBack() {
        window.history.back();
      }
      </script>
      

      JS会打开你之前的浏览器窗口,这意味着它保持不变。下载由参考启动。然后 ref 会导致你的flask-route函数所在的位置。

      【讨论】:

        猜你喜欢
        • 2017-10-12
        • 1970-01-01
        • 2017-12-02
        • 1970-01-01
        • 1970-01-01
        • 2018-03-24
        • 1970-01-01
        • 2019-04-01
        • 1970-01-01
        相关资源
        最近更新 更多