【问题标题】:Flask to render a page and then redirect to an external site?Flask 渲染页面然后重定向到外部站点?
【发布时间】:2022-01-01 01:38:35
【问题描述】:

在 python 脚本在后台成功后,我试图通过烧瓶重定向到外部站点(例如:google.com)。我不确定如何同时重定向和呈现模板。

这是烧瓶代码:


@app.route ("/result",methods=['POST','GET'])  
def result():
    if request.method == "POST":
        ip1=request.form.get('ip')
        output=subprocess.getstatusoutput(["ping -c 2 " +str(ip1)])
        out=output[1]
        ec=output[0]
        return render_template("home.html",out=output[1])
        sleep(3)                                            // Time given so that the output of ping command above gets printed in html page 
        return redirect ("http://www.google.com/",code=307) // Sample External site
 

The above code works till rendering the page "home.html" and prints the output from "ping" command , but doesn't redirect upon successful execution . Is there a way where we can get the redirect based on the exit code of a command's success or show a failure message on error exit code       

【问题讨论】:

    标签: python html flask redirect


    【解决方案1】:

    我相信当您在 (-3) 行返回模板时,您的方法就完成了。

    在我看来,您想向客户端发送重定向标头,但您已经发送了一些内容。你做不到。

    我的想法:保留 return render_template 部分,稍后通过 javascript (check here) 执行重定向

    【讨论】:

    • 感谢您的回复。 javascript重定向确实有效,但是只有当flask app中的子进程成功时,重定向才能起作用?
    • Flask 重定向通过向客户端发送 HTTP 标头来工作。因此,只有当你不需要在客户端写任何东西时它才能工作。如果是这种情况,请尝试: from flask import Flask,redirect return redirect("stackoverflow.com")
    • 我稍微修改了代码,并且重定向工作如你所说:)。还有一种方法可以让我们从一条路线获取表单输入以在另一条路线上工作吗?例如 -> ip1=request.form.get('ip') 从路由(/home)到烧瓶上的另一条路由(/redir)?
    猜你喜欢
    • 1970-01-01
    • 2013-04-19
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多