Skip to content

Simplifying with Blueprints

Following PEP 20 which states that “Simple is better than complex”, we will be simplifying our code by using blueprints. Blueprints are a way to organize a group of related views and other code. They are registered with the application and can be used to create a modular application.

  • app.py

This gets turned into a tree structure like this:

  • app.py
  • blog.py

Creating a Blueprint

To create a blueprint, we need to create a new file called blog.py. We will then create a blueprint object and define the routes for the blog.

from flask import Blueprint
bp = Blueprint('blog', __name__)
@bp.route('/')
def index():
return 'Blog Index'
@bp.route('/post/<int:id>')
def post(id: int):
return f'Post {id}'

We then need to register the blueprint with the application in app.py.

from flask import Flask
app = Flask(__name__)
from blog import bp as blog_bp
app.register_blueprint(blog_bp)