关于#python#的问题:为什么在宝塔里面不能重定向到result.html

为什么在宝塔里面不能重定向到result.html

@app.route('/prediction', methods=["GET", "POST"])
def prediction():
        lg = joblib.load(r"/static/lg_models/Logistic.m")
        prediction = lg.predict_proba(input_features)[0][1]
        return redirect(url_for('result'))
    return render_template('prediction.html')




从你的代码中看,你试图在 Flask 应用中使用 redirect 来重定向到一个叫做 'result' 的页面。然而,url_for 需要一个函数名,而不是一个静态的URL。

首先,你需要定义一个名为 result 的路由,这样 Flask 才知道当 'result' URL 被请求时应该运行哪个函数。例如:

@app.route('/result')
def result():
    return render_template('result.html')

然后,你可以使用 url_for 函数来生成 'result' 页面的 URL。注意,你需要将 'result' 传递给 url_for 函数,而不是直接写 'result'。例如:

return redirect(url_for('result'))

这样,当 '/prediction' URL 被请求并且 prediction 函数运行完成后,redirect 函数会告诉 Flask 将请求重定向到 '/result' URL。然后,result 函数会被运行并返回 'result.html' 页面。

另外,注意你的 return 语句的嵌套可能有问题。你需要在 prediction() 函数的末尾返回 redirect(url_for('result')),否则这个 redirect 不会被执行。例如:

@app.route('/prediction', methods=["GET", "POST"])
def prediction():
        lg = joblib.load(r"/static/lg_models/Logistic.m")
        prediction = lg.predict_proba(input_features)[0][1]
        return redirect(url_for('result'))  # 这里应该是在 prediction() 函数的末尾

希望这个解答能帮到你!

【以下回答由 GPT 生成】

在代码中,问题出在重定向的目标URL未指定具体的result.html文件。在redirect函数中,需要传入目标页面的URL,而不仅仅是函数名。另外,如果需要在重定向时将数据传递到result.html页面,可以使用url_for函数的参数来传递。

以下是修正后的代码示例:

@app.route('/prediction', methods=['GET', 'POST'])
def prediction():
    lg = joblib.load(r'/static/lg_models/Logistic.m')
    prediction = lg.predict_proba(input_features)[0][1]
    return redirect(url_for('result'))   # 将重定向的目标URL修改为result.html

@app.route('/result', methods=['GET', 'POST'])   # 添加result.html对应的路由
def result():
    return render_template('result.html')   # 返回result.html页面

return render_template('prediction.html')

希望这个解决方案对您有所帮助。如果您有其他问题,请随时询问。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^