Welcome to the exciting world of Flask Blueprints! In this lesson, we'll explore the benefits of using Blueprints, learn how to create and use them, and see practical examples of their application.
Blueprints in Flask are a way to structure large applications by dividing them into smaller, reusable modules. They help keep your code organized, manageable, and easier to maintain.
š” Pro Tip: Think of Blueprints as mini-applications within your main application.
To create a Blueprint, follow these simple steps:
Flask module.# my_blueprint/__init__.py
from flask import Blueprint
my_blueprint = Blueprint('my_blueprint', __name__)app object.# app.py
from my_blueprint import my_blueprint
app = Flask(__name__)
app.register_blueprint(my_blueprint)# my_blueprint/routes.py
from flask import Blueprint, render_template
@my_blueprint.route('/')
def home():
return render_template('home.html')url_for() function.<!-- templates/home.html -->
<a href="{{ url_for('my_blueprint.home') }}">Home</a>Let's create a simple Blueprint for a blog application, with routes for displaying a list of posts and individual posts.
# blog/__init__.py
from flask import Blueprint
blog = Blueprint('blog', __name__)
# routes.py
@blog.route('/posts')
def posts_list():
# Load posts from database
posts = [
{'title': 'Post 1', 'content': 'Content 1'},
{'title': 'Post 2', 'content': 'Content 2'},
]
return render_template('blog/posts_list.html', posts=posts)
@blog.route('/posts/<int:post_id>')
def post(post_id):
# Load post from database by ID
post = {
'title': 'Post 1',
'content': 'Content 1',
}
return render_template('blog/post.html', post=post)Which Flask feature helps you structure large applications into smaller, reusable modules?
That's all for this lesson! In the next tutorial, we'll dive deeper into Blueprints, exploring more advanced features and best practices. Stay tuned! š