flask - 为什么路由“/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")
解决方案
您不能将路由注册到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/。
推荐阅读
- oop - 通过字段、方法或 getter 公开 BLOC 流
- python - 使用 pandas GroupBy 检查组中的所有元素是否相等
- node.js - GraphQL:如何嵌套创建模式?
- c++ - QTimer:“多次超时”可能吗?
- javascript - 如何让我的“urls”变量正确更新?
- firebase - 如何获取文档范围
- php - 适用于 PHP 的 S3 S3EncryptionClient AWS 开发工具包:从实例配置文件元数据服务器检索凭证时出错
- c++ - 如何使用 gcc 在 mac 上编译 wine 32 位
- java - 用更少的时间进行更多的迭代?
- regex - PowerShell正则表达式过滤通用差异文件