【问题标题】:How to make flask to send a file and then redirect?如何让烧瓶发送文件然后重定向?
【发布时间】:2017-05-21 22:40:12
【问题描述】:

我希望我的烧瓶应用程序发送一个文件,然后重定向到主页。

def create_pdf(**kwargs):
    page = PdfManager(**kwargs)
    pdf_out = page.create_pdf()
    response = make_response(pdf_out)
    # redirect(url_for('home'))
    response.headers['Content-Disposition'] = "attachment; filename=pdf-test.pdf"
    response.mimetype = 'application/pdf'
    return response

app.route('/', methods=['GET', 'POST'])
def home():
    create_pdf(foo='bar')

这段代码在响应时正确吐出 pdf 文件,但我无法在下载 pdf 文件后使页面刷新或重定向。我不能使用flask的send_from_directory方法,因为这个pdf文件是使用StringIoPdfFileWriter对象动态生成的。

【问题讨论】:

    标签: python pdf flask


    【解决方案1】:

    您可以使用 javascript 使“/”路径返回一个 html 响应,例如:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <script>
            setTimeout(function(){
                document.location = "/redirect-uri";
            }, 500)
        </script>
    </head>
    <body>
        <iframe width="0" height="0" src="/path-to-pdf.pdf"/>
    </body>
    </html>

    如果 pdf 是动态生成的,您还应该像这样提供 pdf url

    @route('/path-to-pdf.pdf')
    def pdf_generator():
        return create_pdf()
    

    【讨论】:

      【解决方案2】:

      更好的方法可能是让 javascript 处理提交表单以及重定向:

      <form name="createPdf">
          <!-- Your fields etc. here -->
          <a href="javascript:submitAndRedirect()">
              <button>Submit</button> <!-- NB do not use type=submit -->
          </a>
      </form>
      
      <script type="text/javascript">
          function submitAndRedirect() {
              document.createPdf.submit();
              setTimeout(function() {
                  location.href = YOUR_REDIRECT_URL_HERE;
              }, 500);
          }
      </script>
      

      如果需要,可以从 python 中注入 redirectUrl,如下所示:

      return render_template("create_pdf.html", redirect_url=url_for("whatever"))
      

      然后在你的javascript中:

      var redirectUrl = '{{ redirect_url }}';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多