ankush981
ankush981

Reputation: 5417

Can't get flask blueprint to work

I'm learning Blueprints in Flask and wrote the following short script to test how urls can be served from the blueprint:

from flask import Flask, Blueprint

app = Flask(__name__)
bp = Blueprint('bp', __name__)

app.register_blueprint(bp, url_prefix='/bp')

@bp.route('/', methods=['GET', 'POST'])
def bp_home():
    return("And a new blueprint is born!")

@app.route('/', methods=['GET', 'POST'])
def app_home():
    return("App home is here!")

app.run()

I was expecting that while http://localhost:5000 should give me the string "App home is here!", http://localhost:5000/bp should return "And a new blueprint is born!". Unfortunately, only the former works; the latter one gives me a 404. What am I doing wrong?

Upvotes: 0

Views: 1331

Answers (1)

Matt Healy
Matt Healy

Reputation: 18531

You have to call app.register_blueprint after you've defined the routes for the blueprint.

from flask import Flask, Blueprint

app = Flask(__name__)
bp = Blueprint('bp', __name__)


@bp.route('/', methods=['GET', 'POST'])
def bp_home():
    return("And a new blueprint is born!")

@app.route('/', methods=['GET', 'POST'])
def app_home():
    return("App home is here!")

app.register_blueprint(bp, url_prefix='/bp')

app.run()

Upvotes: 1

Related Questions