0
0
Flaskframework~30 mins

Blueprint best practices in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Blueprint Best Practices in Flask
📖 Scenario: You are building a simple Flask web application that has two parts: a main page and a user page. To keep your code organized, you will use Flask Blueprints to separate these parts.
🎯 Goal: Create two Flask Blueprints named main_bp and user_bp. Register them in the Flask app with URL prefixes. Each Blueprint should have one route that returns a simple message.
📋 What You'll Learn
Create a Flask app instance named app
Create a Blueprint named main_bp with the name 'main' and import name __name__
Create a Blueprint named user_bp with the name 'user' and import name __name__
Add a route / to main_bp that returns the string 'Welcome to the main page!'
Add a route /profile to user_bp that returns the string 'User profile page'
Register main_bp with the Flask app with URL prefix '' (no prefix)
Register user_bp with the Flask app with URL prefix /user
💡 Why This Matters
🌍 Real World
Blueprints help organize large Flask apps by grouping related routes and code, making the app easier to maintain.
💼 Career
Understanding Blueprints is essential for backend developers working with Flask to build scalable and clean web applications.
Progress0 / 4 steps
1
Create the Flask app and main Blueprint
Import Flask and Blueprint from flask. Create a Flask app instance called app. Create a Blueprint called main_bp with the name 'main' and import name __name__.
Flask
Need a hint?

Use app = Flask(__name__) to create the app. Use Blueprint('main', __name__) to create the main blueprint.

2
Create the user Blueprint
Create a Blueprint called user_bp with the name 'user' and import name __name__.
Flask
Need a hint?

Use Blueprint('user', __name__) to create the user blueprint.

3
Add routes to the Blueprints
Add a route / to main_bp that returns the string 'Welcome to the main page!'. Add a route /profile to user_bp that returns the string 'User profile page'.
Flask
Need a hint?

Use @main_bp.route('/') and @user_bp.route('/profile') decorators to add routes.

4
Register Blueprints with the Flask app
Register main_bp with the Flask app using app.register_blueprint(main_bp, url_prefix=''). Register user_bp with the Flask app using app.register_blueprint(user_bp, url_prefix='/user').
Flask
Need a hint?

Use app.register_blueprint() to connect blueprints to the app with the correct URL prefixes.