Flask - Static Files
by
Jeremy Canfield |
Updated: January 17 2023
| Flask articles
Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.
- Model -> models.py
- View -> views.py
- Controller -> __init__.py
Typically, your CSS files will be stored in the static directory, something like this.
├── main.py
├── database (directory)
│ ├── example.db
├── my-project (directory)
│ ├── __init__.py
│ ├── views.py
│ ├── models.py
│ ├── templates (directory)
│ │ ├── base.html
│ │ ├── home.html
│ │ ├── results.html
│ └── static (directory)
│ └── custom.css
Let's say __init__.py contains the following. In this example, app.static_folder and app.static_url_path are used to make style.css available from the static folder.
from flask import Flask
def my_website():
app = Flask(__name__)
from .views import views
app.register_blueprint(views, url_prefix='/')
app.static_folder = 'static'
app.static_url_path = '/static'
return app
And base.html could look something like this, using url_for to get style.css from the static folder.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet">
</head>
<body>
<title>{% block title %}Home{% endblock %}</title>
{% block content %} {% endblock %}
</body>
</html>
Did you find this article helpful?
If so, consider buying me a coffee over at