I have a flask project with following three files:
# app.py
from flask import Flask
from userbp import bp
app = Flask(__name__)
app.register_blueprint(bp)
@app.route("/")
def index():
return "Hello, world"
# userbp.py
from flask import Blueprint
bp = Blueprint("user", __name__, url_prefix="/user")
# user_views.py
from userbp import bp
@bp.route("/<string:name>")
def greet(name):
return f"Hello, {name}! How are you?"
Here is the structure of this project's root directory:
.
├── __pycache__
│ ├── app.cpython-311.pyc
│ └── userbp.cpython-311.pyc
├── app.py
├── user_views.py
└── userbp.py
It is not working as expected, hitting the URL /John
gives a 494 not found error. While if I move the greet
view from user_views.py
to userbp.py
, it works as expected.
Why is it so?
How to fix this problem?
TYPO: It was actually 404 error Thanks.
There a 2 solutions for this problem.
sub-route
should define with same as blueprint
initiations.So your code should be like this
# app.py
from flask import Flask
# import blueprint from userbp.py
from userbp import bp
app = Flask(__name__)
app.register_blueprint(bp)
@app.route("/")
def index():
return "Hello, world"
if __name__ == "__main__":
app.run()
# userbp.py
from flask import Blueprint
# initialization of blueprint
bp = Blueprint("user", __name__, url_prefix="/user")
## implementation of sub-route blueprints
@bp.route("/<string:name>")
def greet(name):
return f"Hello, {name}! How are you?"
# app.py
from flask import Flask
# import blueprint from user_views.py
from user_views import bp
app = Flask(__name__)
app.register_blueprint(bp)
@app.route("/")
def index():
return "Hello, world"
if __name__ == "__main__":
app.run()
# userbp.py
from flask import Blueprint
bp = Blueprint("user", __name__, url_prefix="/user")
# user_views.py
from userbp import bp
@bp.route("/<string:name>")
def greet(name):
return f"Hello, {name}! How are you?"
So like this will work.
And the problem, why it's show error not found cause you accessing the wrong routes.
It Should be like this http://localhost:5000/user/john.
Cause in blueprint your code is defined to sub-route user
in here
bp = Blueprint("user", __name__, url_prefix="/user")