Flask Blueprints Explained: How to Structure Your Flask App
Flask Blueprints make it easier to organize your code as your application grows. Instead of putting all routes and logic in a single file, Blueprints let you split your app into smaller, reusable modules.
In this tutorial, you'll learn how to structure your Flask project using Blueprints.
🧱 Example Project Structure
Here's a simple folder structure for a Flask app using Blueprints:
myapp
│
├── app
│ ├── __init__.py
│ ├── home.py
│ ├── auth.py
│ ├── info.py
│
└── run.py
Each file inside the app folder will contain its own Blueprint.
⚙️ Step 1: Create Blueprints
/app/home.py
from flask import Blueprint
home_bp = Blueprint('home_bp', __name__)
@home_bp.route('/')
def index():
return 'Index Page!'
/app/auth.py
from flask import Blueprint
auth_bp = Blueprint('auth_bp', __name__)
@auth_bp.route('/login')
def login():
return 'Login Page!'
@auth_bp.route('/logout')
def logout():
return 'Logout Page!'
/app/info.py
from flask import Blueprint
info_bp = Blueprint('info_bp', __name__)
@info_bp.route('/about')
def about():
return 'About Page!'
@info_bp.route('/contact')
def contact():
return 'Contact Page!'
🏗️ Step 2: Register Blueprints in __init__.py
Inside your app/__init__.py, create and configure your Flask application.
from flask import Flask
def create_app():
app = Flask(__name__)
from .home import home_bp
from .auth import auth_bp
from .info import info_bp
app.register_blueprint(home_bp)
app.register_blueprint(auth_bp)
app.register_blueprint(info_bp)
return app
🚀 Step 3: Run Your Flask App
Finally, run your application with the run.py file:
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
✅ Final Thoughts
Flask Blueprints help you build scalable applications by dividing your routes into separate, manageable components. As your project grows, this structure keeps your code cleaner and easier to maintain.
Next, try adding templates, static files, or even API routes to each Blueprint for a more modular setup.