My Flask application is not recognizing/using the two defined routes in auth.py
, how come?
File structure
Error Msg:
Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Routes
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)
app.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")
auth.py
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")
CodePudding user response:
You can't register routes to current_app
, instead you have to use a class called Blueprint
which is built exactly for this purpose (splitting application into multiple files).
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")
See https://flask.palletsprojects.com/en/2.0.x/blueprints/ for more information.
CodePudding user response:
It seems like you have at least two files in which you have these routes. In your app.py file you have /home and /profile, they both work. They work because you initialised the Flask application over there.
Flask offers Blueprints to split up your application. You could create a blueprint called auth for example.
There is a specific tutorial on this subject as well.
I suggest moving the initialisation of the app variable to the __init__.py
file and creating a create_app() method that returns app. In this method you can register your blueprints as well.
This method would look like:
def create_app():
app = Flask(__name__)
from . import app as application, auth
app.register_blueprint(auth.bp)
app.register_blueprint(application.bp)
return app
Your auth.py
file, for example, would look like:
from flask import Blueprint, render_template
bp = Blueprint('auth', __name__)
@bp.route("/login")
def login():
return render_template("login.html")
@bp.route("/register")
def register():
return render_template("register.html")