Blueprints

Back

Loading concept...

πŸ—οΈ Flask Blueprints: Building Your App Like LEGO Blocks


🎭 The Story: Your Flask App is Growing Up!

Imagine you have a toy box with ALL your toys insideβ€”cars, dolls, blocks, action figuresβ€”everything mixed together. When you want to find your favorite car, you dig through EVERYTHING. Messy, right?

Now imagine you have separate boxes: one for cars πŸš—, one for dolls 🎎, one for blocks 🧱. Finding anything becomes super easy!

Flask Blueprints are like those separate boxes. They help you organize your growing Flask app into neat, tidy pieces!


πŸ“– What Are Blueprints?

A Blueprint is a mini Flask app that doesn’t run by itself. Think of it like a room in a house:

  • The house = Your main Flask app
  • Each room = A Blueprint (kitchen, bedroom, bathroom)
  • Each room has its own stuff but belongs to the house
# A Blueprint is like saying:
# "Hey, I'm the KITCHEN room!"
# "I handle all cooking stuff!"

Why Use Blueprints?

Without Blueprints 😡 With Blueprints 😊
All code in one file Code in separate files
Hard to find things Easy to find things
Team can’t work together Team works on different parts
Messy like a toy pile Organized like labeled boxes

πŸ”§ Creating Blueprints

Creating a Blueprint is like naming a new room in your house!

# In auth/routes.py
from flask import Blueprint

# Create a Blueprint named 'auth'
auth_bp = Blueprint('auth', __name__)

# Now auth_bp is your "auth room"!

The Magic Words Explained:

Blueprint('auth', __name__)
#          ↑        ↑
#       name    where am I?
  • 'auth' = The name of this Blueprint (like β€œkitchen”)
  • __name__ = Tells Flask where this Blueprint lives

Real Example - User Authentication Blueprint:

# auth/routes.py
from flask import Blueprint

auth_bp = Blueprint('auth', __name__)

# This blueprint handles:
# - Login
# - Logout
# - Sign up

πŸ“ Registering Blueprints

Creating a Blueprint alone does nothingβ€”like buying furniture but leaving it in the truck! You must register it with your main app.

# app.py (main file)
from flask import Flask
from auth.routes import auth_bp

app = Flask(__name__)

# REGISTER the blueprint!
app.register_blueprint(auth_bp)

# Now auth_bp is part of your app! πŸŽ‰

Think of it like:

graph TD A["🏠 Main Flask App"] --> B["πŸ“¦ Register Blueprint"] B --> C["βœ… Blueprint Now Active!"]

πŸ›€οΈ Blueprint Routes

Routes inside a Blueprint work exactly like normal routesβ€”but they belong to that Blueprint’s β€œroom”!

# auth/routes.py
from flask import Blueprint

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login')
def login():
    return 'Login Page!'

@auth_bp.route('/logout')
def logout():
    return 'Goodbye!'

@auth_bp.route('/signup')
def signup():
    return 'Create Account!'

What Just Happened?

Route What it does
/login Shows login page
/logout Says goodbye
/signup Create new account

All these routes belong to auth_bpβ€”they’re organized together!


🎨 Blueprint Templates

Each Blueprint can have its own templates folderβ€”like each room having its own decorations!

Folder Structure:

my_app/
β”œβ”€β”€ app.py
β”œβ”€β”€ auth/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ routes.py
β”‚   └── templates/    ← Auth's templates!
β”‚       └── login.html
└── blog/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ routes.py
    └── templates/    ← Blog's templates!
        └── post.html

Setting Up Template Folder:

# auth/routes.py
auth_bp = Blueprint(
    'auth',
    __name__,
    template_folder='templates'  # ← Magic!
)

@auth_bp.route('/login')
def login():
    return render_template('login.html')

How Flask Finds Templates:

graph TD A["render_template"] --> B{Check Blueprint folder} B -->|Found| C["βœ… Use it!"] B -->|Not Found| D{Check main templates} D -->|Found| E["βœ… Use it!"] D -->|Not Found| F["❌ Error!"]

πŸ“ Blueprint Static Files

Static files are things that don’t changeβ€”images, CSS, JavaScript. Each Blueprint can have its own!

Folder Structure:

my_app/
β”œβ”€β”€ auth/
β”‚   β”œβ”€β”€ routes.py
β”‚   └── static/        ← Auth's static files!
β”‚       β”œβ”€β”€ style.css
β”‚       └── logo.png

Setting Up Static Folder:

# auth/routes.py
auth_bp = Blueprint(
    'auth',
    __name__,
    template_folder='templates',
    static_folder='static'  # ← Add this!
)

Using Blueprint Static Files in HTML:

<!-- In auth/templates/login.html -->
<link rel="stylesheet"
  href="{{ url_for('auth.static',
           filename='style.css') }}">

Key Point:

Use 'auth.static' not just 'static'β€”the Blueprint name comes first!


🏷️ URL Prefixes for Blueprints

Here’s the superpower: You can add a prefix to ALL routes in a Blueprint!

Without Prefix:

# Routes are: /login, /logout, /signup
app.register_blueprint(auth_bp)

With Prefix:

# Routes become: /auth/login, /auth/logout
app.register_blueprint(
    auth_bp,
    url_prefix='/auth'
)

Real-World Example:

# app.py
from flask import Flask
from auth.routes import auth_bp
from blog.routes import blog_bp
from shop.routes import shop_bp

app = Flask(__name__)

# Register with prefixes
app.register_blueprint(auth_bp, url_prefix='/auth')
app.register_blueprint(blog_bp, url_prefix='/blog')
app.register_blueprint(shop_bp, url_prefix='/shop')

Now Your URLs Are:

Blueprint Prefix Example Routes
auth_bp /auth /auth/login, /auth/signup
blog_bp /blog /blog/post, /blog/new
shop_bp /shop /shop/cart, /shop/buy

Visual Map:

graph TD A["🏠 myapp.com"] --> B["/auth"] A --> C["/blog"] A --> D["/shop"] B --> E["/auth/login"] B --> F["/auth/signup"] C --> G["/blog/posts"] C --> H["/blog/new"] D --> I["/shop/cart"] D --> J["/shop/buy"]

🎯 Complete Example: Putting It All Together!

Project Structure:

my_awesome_app/
β”œβ”€β”€ app.py              ← Main app
β”œβ”€β”€ auth/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ routes.py       ← Auth Blueprint
β”‚   β”œβ”€β”€ templates/
β”‚   β”‚   └── login.html
β”‚   └── static/
β”‚       └── auth.css
└── blog/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ routes.py       ← Blog Blueprint
    └── templates/
        └── post.html

auth/routes.py:

from flask import Blueprint
from flask import render_template

auth_bp = Blueprint(
    'auth',
    __name__,
    template_folder='templates',
    static_folder='static'
)

@auth_bp.route('/login')
def login():
    return render_template('login.html')

@auth_bp.route('/logout')
def logout():
    return 'Logged out!'

blog/routes.py:

from flask import Blueprint
from flask import render_template

blog_bp = Blueprint(
    'blog',
    __name__,
    template_folder='templates'
)

@blog_bp.route('/')
def all_posts():
    return 'All blog posts!'

@blog_bp.route('/new')
def new_post():
    return 'Write new post!'

app.py:

from flask import Flask
from auth.routes import auth_bp
from blog.routes import blog_bp

app = Flask(__name__)

# Register blueprints with prefixes
app.register_blueprint(auth_bp, url_prefix='/auth')
app.register_blueprint(blog_bp, url_prefix='/blog')

@app.route('/')
def home():
    return 'Welcome Home!'

if __name__ == '__main__':
    app.run(debug=True)

🌟 Quick Summary

Concept What It Does Example
Create Make a new Blueprint Blueprint('name', __name__)
Register Add Blueprint to app app.register_blueprint(bp)
Routes Define paths in Blueprint @bp.route('/path')
Templates Blueprint’s own HTML files template_folder='templates'
Static Blueprint’s own CSS/JS/images static_folder='static'
Prefix Add prefix to all routes url_prefix='/api'

πŸŽ‰ You Did It!

Now you know how to organize your Flask app like a pro! Blueprints keep your code clean, your team happy, and your app ready to grow!

Remember: Blueprints are rooms in your house. Each room has its own stuff, but they all belong to the same home! 🏠

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.