Overview
Blueprints are Flask’s way of organizing applications into modular components. They allow you to structure large applications into smaller, reusable pieces.What are Blueprints?
A blueprint is a template for generating a “section” of a web application. You can think of it as a mini-application that can be registered on the main Flask app.Why Use Blueprints?
- Modularity: Organize code by feature or functionality
- Reusability: Share blueprints across projects
- Scalability: Large apps become manageable
- Team Development: Different teams work on different blueprints
- Namespace: Avoid naming conflicts with prefixes
Creating a Blueprint
Fromblueprints.py:18-54:
Registering Blueprints
Register blueprints with the Flask application:Blueprint Parameters
Basic Parameters
URL Prefix
Add a prefix to all blueprint routes:Subdomain
Mount blueprint on a subdomain:Blueprint Structure
Recommended Directory Layout
Example Blueprint Module
myapp/admin/__init__.py:
myapp/admin/views.py:
Blueprint Routes
Defining Routes
Blueprints use the same routing decorators as the main app:Endpoint Names
Blueprint routes get prefixed endpoint names:Blueprint Resources
Templates
Fromtemplating.py:98-107, blueprints can have their own templates:
- Blueprint’s
templatesfolder - Application’s
templatesfolder
Static Files
Fromblueprints.py:82-102, serve static files from blueprints:
Resource Files
Fromblueprints.py:104-129, open blueprint resources:
Blueprint Hooks
Before Request
After Request
Teardown
Error Handlers
Context Processors
Add variables to blueprint templates:Nested Blueprints
Blueprints can be nested (Flask 2.0+):Blueprint Factories
Create configurable blueprints:URL Generation
Within Blueprint
From Templates
CLI Commands
Add CLI commands to blueprints:Application Factory Pattern
Combine blueprints with application factories:Best Practices
Organize by Feature
Group related functionality together, not by type
Clear Naming
Use descriptive blueprint names that reflect their purpose
Avoid Circular Imports
Import views at the end of init.py
Use Factories
Combine with application factory pattern for flexibility
Common Patterns
API Blueprint
Auth Blueprint
Related Concepts
- Application - Flask application object
- Routing - URL routing
- Templates - Template organization
