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.
Blueprint static files in Flask
bp = Blueprint('name', __name__, static_folder='static', static_url_path='/static')
static_folder is the folder inside the blueprint where static files live.static_url_path is the URL prefix to access these static files in the browser.bp = Blueprint('blog', __name__, static_folder='static', static_url_path='/blog/static')
bp = Blueprint('admin', __name__, static_folder='assets')
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.
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)
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.
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.