Simplifying with Blueprints
A simple website built using flask
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}'
You can set the path that the blueprint will be registered at by passing the url_prefix argument to the Blueprint constructor.
bp = Blueprint('blog', __name__, url_prefix='/blog')
This will register the blueprint at /blog instead of /.
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)
- Visit http://127.0.0.1:5000/ to see
Blog Index - Visit http://127.0.0.1:5000/post/1 to see
Post 1