Modular Routing with Flask Blueprints
Modular Routing with Flask Blueprints
Putting all routes, models, and helper functions in a single app.py file works for prototypes, but enterprise applications quickly become unmaintainable as they grow to dozens of endpoints.
Flask Blueprints provide a modular pattern for dividing an application into reusable, self-contained components—such as an authentication module, an administrative portal, and a public API.
1. What is a Blueprint?
A Blueprint is essentially a recording object for application components (routes, error handlers, static files, and templates). Instead of registering routes directly with app, you register them with the Blueprint. Later, the Blueprint is registered onto the core application instance.
+-------------------------------------------------------------------------------+
| Flask Application (app) |
+-------------------------------------------------------------------------------+
| | |
v v v
+----------------+ +----------------+ +---------------+
| auth_bp | | courses_bp | | api_bp |
| prefix: /auth | | prefix: /courses| | prefix: /api |
+----------------+ +----------------+ +---------------+
| /login | | / | | /v1/users |
| /logout | | /<slug> | | /v1/checkout |
| /register | | /enroll | | /v1/analytics |
+----------------+ +----------------+ +---------------+2. Directory Structure for Blueprint-Driven Applications
3. Defining a Blueprint
In app/auth/routes.py:
4. Registering Blueprints with the Application
In app/__init__.py:
5. Reverse Routing with Blueprint Namespaces
When using Blueprints, url_for() requires the blueprint name as a prefix separated by a dot:
Practice Quiz
admin resolved using url_for()?url_prefix parameter do when registering a blueprint?static_folder and template_folder?The Application Factory Pattern (create_app)
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Role-Based Access Control & Custom Decorators | The Application Factory Pattern (create_app) |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.