Flask Static Files & Blueprints

πŸ“ Static files

myproject/
β”œβ”€β”€ app.py
└── static/
    β”œβ”€β”€ style.css
    └── images/logo.png
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<img src="{{ url_for('static', filename='images/logo.png') }}">
app = Flask(__name__, static_folder="assets", static_url_path="/files")   # customize defaults

🧩 Blueprints

# blog/routes.py
from flask import Blueprint, render_template
 
blog_bp = Blueprint("blog", __name__, template_folder="templates")
 
@blog_bp.route("/")
def index():
    return render_template("blog/index.html")
 
@blog_bp.route("/<int:post_id>")
def show_post(post_id):
    return render_template("blog/post.html", post_id=post_id)
# app.py
from blog.routes import blog_bp
app.register_blueprint(blog_bp, url_prefix="/blog")

β†’ /blog/ = index(), /blog/42 = show_post(42)

{{ url_for('blog.index') }}                 {# blueprint routes need "blueprintname." prefix #}
{{ url_for('blog.show_post', post_id=42) }}

Forgetting the blueprintname. prefix in url_for inside a blueprint = error.

πŸ—‚οΈ Layout with blueprints

myproject/
β”œβ”€β”€ app.py
β”œβ”€β”€ blog/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ routes.py
β”‚   └── templates/blog/index.html    # nested folder avoids naming collisions
β”œβ”€β”€ auth/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── routes.py
└── static/

🎯 Blueprint-specific static + hooks

blog_bp = Blueprint("blog", __name__, static_folder="static", static_url_path="/blog-static")
 
@blog_bp.before_request
def check_maintenance():
    if maintenance_mode():
        return "Under maintenance", 503

πŸ”— Next

Flask Forms & WTForms Β· Flask Configuration & Application Factory