🎓 A1Learner
🔍
0 of 50 lessons completed

What Is a Flask Blueprint

A blueprint is a bundle of routes kept together. It groups the routes of one part of a site.

Make the app and the blueprint

This line imports Flask and Blueprint together. The blueprint is named shop.

from flask import Flask, Blueprint

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

Add a route to the blueprint

The route attaches to shop, not to the app. The decorator comes from the blueprint.

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

Register, then ask

The app registers the blueprint and gains its routes. The test client asks for /cart and prints the page.

app.register_blueprint(shop)

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

Example

from flask import Flask, Blueprint

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

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

app.register_blueprint(shop)

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

Key points

  • Blueprint("shop", __name__) makes a blueprint named shop.
  • Routes attach to the blueprint, not to the app.
  • The app gains the routes when it registers the blueprint.
  • One site holds many blueprints.

In this example, the blueprint shop holds one route, /cart. The app registers the blueprint and gains the route. The test client asks for /cart and prints the page.

Note

A blueprint alone serves nothing until it is registered.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is a Flask blueprint?