首页 > 解决方案 > 为什么路由“/login”和“/register”不起作用?

问题描述

我的 Flask 应用程序无法识别/使用中定义的两个路由auth.py,这是怎么回事?


文件结构

文件结构

错误信息: Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

路线

http://127.0.0.1:5000/home (WORKS)
http://127.0.0.1:5000/profile (WORKS)
http://127.0.0.1:5000/login (DOES NOT WORK)
http://127.0.0.1:5000/register (DOES NOT WORK)

应用程序.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/home")
def home():
    return render_template("index.html")

@app.route("/profile")
def profile():
    return render_template("profile.html")

授权文件

from flask import current_app as app, render_template

@app.route("/login")
def login():
    return render_template("login.html")

@app.route("/register")
def register():
    return render_template("register.html")

标签: flaskroutes

解决方案


您不能将路由注册到current_app,而是必须使用Blueprint专门为此目的构建的名为的类(将应用程序拆分为多个文件)。

app.py

from flask import Flask, render_template
from auth import auth_bp

app = Flask(__name__)

# Register the blueprint
app.register_blueprint(auth_bp)

@app.route("/home")
def home():
    return render_template("index.html")

@app.route("/profile")
def profile():
    return render_template("profile.html")

auth.py

from flask import Blueprint, render_template

# Initialize the blueprint
auth_bp = Blueprint('auth', __name__)

@auth_bp.route("/login")
def login():
    return render_template("login.html")

@auth_bp.route("/register")
def register():
    return render_template("register.html")

有关更多信息,请参阅https://flask.palletsprojects.com/en/2.0.x/blueprints/


推荐阅读