🎓 A1Learner
🔍
0 of 50 lessons completed

Registering Flask Blueprints

Registering a blueprint adds its routes to the app. The app serves the routes after the call.

Make the app and two blueprints

This line imports Flask and Blueprint together. The app gains two blueprints below.

from flask import Flask, Blueprint

app = Flask(__name__)
shop = Blueprint("shop", __name__)
blog = Blueprint("blog", __name__)

Add a route to each blueprint

Each blueprint holds one route. The routes attach to their own blueprint.

@shop.route("/cart")
def cart():
    return "Your cart"

@blog.route("/posts")
def posts():
    return "All posts"

Register both, then ask

The app registers both blueprints. The test client asks for each route and prints the pages.

app.register_blueprint(shop)
app.register_blueprint(blog)

client = app.test_client()
print(client.get("/cart").data.decode())
print(client.get("/posts").data.decode())

Example

from flask import Flask, Blueprint

app = Flask(__name__)
shop = Blueprint("shop", __name__)
blog = Blueprint("blog", __name__)

@shop.route("/cart")
def cart():
    return "Your cart"

@blog.route("/posts")
def posts():
    return "All posts"

app.register_blueprint(shop)
app.register_blueprint(blog)

client = app.test_client()
print(client.get("/cart").data.decode())
print(client.get("/posts").data.decode())

Key points

  • app.register_blueprint(shop) adds the shop routes.
  • Register each blueprint once, before running.
  • Two blueprints give the app two sets of routes.
  • Routes from different blueprints share one app.

In this example, the shop blueprint holds /cart and the blog blueprint holds /posts. The app registers both blueprints and gains both routes. The test client asks for each route and prints the pages.

Note

Registration happens after the blueprint is made.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does an app gain the routes of a blueprint?