python flask重定向到另一个pag

2024-05-14 12:56:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为login.py的登录页面,它呈现login.html。提交时,我想重定向到呈现mainpage.htmlmainpage.py。但在提交点击它只是不重定向。我得到一个页面未找到错误。网址保持不变

@app.route('/login',methods = ['GET','POST'])
def index():
    try:
        if request.method =='POST':
            db_user = request.form['db_user']
            db_pwd = request.form['db_pwd']
            if (connect(db_user,db_pwd)==1):
                return redirect("/mainpage", code=302)
        else:
            return render_template('login.html')    
    except Exception as e:
        print(("error :", str(e)))
        return render_template('login.html')

重定向选项中应该提到什么?它是html文件名还是py文件名?我尝试使用html文件名、py文件名和@app.route中的名称。但是没有成功


Tags: pyappdbreturn文件名requesthtmlpwd
2条回答

^{}的第一个参数是您希望客户端重定向到的url。可以将url硬编码为第一个参数。还可以使用^{}为给定端点生成url。

例如:

@app.route("/url")
def endpoint():
    return "Test redirect & url_for"

您可以使用redirect(url_for("endpoint"))redirect("/url")重定向到/url

Quickstart指出了使用url_for而不是硬编码url的优点。

404错误的原因:

当重定向到/mainpage时,Flask将在login.py文件中查找路由处理程序,而不是mainpage.py。因为login.py没有/mainpage的路由处理程序,所以它给您一个404。它永远不会到达mainpage.py

你想做什么和可能的解决方案:

你要做的是在不同的文件之间分离路由。为此,您需要显式地告诉Flask路由处理程序在哪里(换句话说,它应该在哪些文件中查找路由处理程序)。

有两种方法:

  1. 请参阅本文档(Larger Applications)以了解如何将文件组织为包。您必须将mainpage.py导入login.py,反之亦然。

  2. 或者使用蓝图:Modular Applications with Blueprints

Please note that you'll only need that if your application has a substantial size. If you have just a few route handlers, you should probably keep it simple with everything in one single file.

相关问题 更多 >

    热门问题