0
0
Flaskframework~5 mins

Blueprint static files in Flask

Choose your learning style9 modes available
Introduction

Blueprint static files let you organize images, CSS, and JavaScript inside parts of your Flask app. This keeps your project neat and easy to manage.

You want to keep static files related to a feature separate from the main app files.
You are building a large Flask app with multiple sections or modules.
You want to reuse a blueprint with its own static files in different projects.
You want to avoid mixing all static files in one folder to reduce confusion.
Syntax
Flask
bp = Blueprint('name', __name__, static_folder='static', static_url_path='/static')
The static_folder is the folder inside the blueprint where static files live.
The static_url_path is the URL prefix to access these static files in the browser.
Examples
This creates a blueprint named 'blog' with its own static files served under '/blog/static'.
Flask
bp = Blueprint('blog', __name__, static_folder='static', static_url_path='/blog/static')
This blueprint uses 'assets' folder for static files and defaults the URL path to '/admin/static'.
Flask
bp = Blueprint('admin', __name__, static_folder='assets')
Sample Program

This Flask app creates a blueprint named 'shop' with its own static folder. The home page returns a link tag to a CSS file inside the blueprint's static folder. The static file URL is generated using url_for with the blueprint's static endpoint.

Flask
from flask import Flask, Blueprint, url_for

bp = Blueprint('shop', __name__, static_folder='static', static_url_path='/static')

app = Flask(__name__)
app.register_blueprint(bp, url_prefix='/shop')

@app.route('/')
def home():
    # Generate URL for a static file inside the blueprint
    css_url = url_for('shop.static', filename='style.css')
    return f'<link rel="stylesheet" href="{css_url}">Hello from Shop!'

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

Static files in blueprints are served automatically by Flask when you set static_folder.

Use url_for('blueprint_name.static', filename='file.ext') to get the correct URL for static files.

Remember to register the blueprint with app.register_blueprint() for it to work.

Summary

Blueprint static files help keep your app organized by grouping static assets with their features.

Set static_folder and optionally static_url_path when creating a blueprint.

Use url_for with the blueprint's static endpoint to link to these files in templates or responses.