Search code examples
pythonpython-3.xflask

routing a view through blueprint in another module doesn't work


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.


Solution

  • There a 2 solutions for this problem.

    • Best practices for blueprint in flask is that 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?"
    
    • If you still want to separate initialization of blueprint and the implementation of sub-route you can do like this.
    # 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")