I have a blueprint, home
, with the prefix /
on my Flask app. The blueprint has a static folder and is configured with the static_folder
argument. However, linking to the blueprint's static files returns a 404 error, even though the file exists and the url looks right. Why doesn't the blueprint serve the static files?
myproject/
run.py
myapp/
__init__.py
home/
__init__.py
templates/
index.html
static/
css/
style.css
myapp/init.py
:
from flask import Flask
application = Flask(__name__)
from myproject.home.controllers import home
application.register_blueprint(home, url_prefix='/')
myapp/home/controllers.py
:
from flask import Blueprint, render_template
home = Blueprint('home', __name__, template_folder='templates', static_folder='static')
@home.route('/')
def index():
return render_template('index.html')
myapp/home/templates/index.html
:
<head>
<link rel="stylesheet" href="{{url_for('home.static', filename='css/style.css')}}">
</head>
<body>
</body>
myapp/home/static/css/style.css
:
body {
background-color: green;
}
Flask automatically creates a static view that serves static files from a folder named static in your application's directory. You can also use the url_for() method to allow for more dynamic URLs. Its use reduces the amount of modification needed in the code if something needs to change in your URL references.
Each Flask Blueprint is an object that works very similarly to a Flask application. They both can have resources, such as static files, templates, and views that are associated with routes. However, a Flask Blueprint is not actually an application. It needs to be registered in an application before you can run it.
Folder structure for a Flask app That folder contains two folders, specifically named static and templates. The static folder contains assets used by the templates, including CSS files, JavaScript files, and images.
Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications.
You are getting a conflict with the Flask static folder and your blueprint. Since the blueprint is mounted at /
, it shares the same static url as the app, but the app's route takes precedence. Change the static url for the blueprint so it doesn't conflict.
home = Blueprint(
'home', __name__,
template_folder='templates',
static_folder='static',
static_url_path='/home-static'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With