Static files
In Flask, static files refer to the files that don’t change, such as CSS, JavaScript, images, and other assets that are served directly to the client's browser. Flask serves static files from the static directory, which you can use to store and organize your project's static assets.
Setting Up Static Files in Flask
- Creating the
staticDirectory: By default, Flask expects static files to be in a directory namedstaticin your application folder.
Project Structure:my_flask_project/ ├── app/ │ ├── __init__.py │ ├── routes.py │ ├── templates/ │ │ └── index.html │ └── static/ │ ├── css/ │ │ └── style.css │ ├── js/ │ │ └── script.js │ └── images/ │ └── logo.png ├── run.py └── config.py - Serving Static Files: Flask automatically serves files from the
staticdirectory. To include a static file in your HTML template, use theurl_forfunction with the'static'endpoint.<!-- templates/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home Page</title> <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> </head> <body> <h1>Welcome to My Flask App!</h1> <img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo"> <script src="{{ url_for('static', filename='js/script.js') }}"></script> </body> </html> - Using the
url_forFunction: Theurl_forfunction generates a URL for the specified endpoint. For static files, it takes the filename as an argument, which should be relative to thestaticdirectory.<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> - Organizing Static Files: It’s good practice to organize your static files into subdirectories within the
staticdirectory, such ascss,js, andimages.
Example: Adding CSS, JavaScript, and Images
Let’s expand on the project example to include static files like CSS, JavaScript, and images.
Project Structure:
my_flask_project/
├── app/
│ ├── __init__.py
│ ├── routes.py
│ ├── templates/
│ │ └── index.html
│ └── static/
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── script.js
│ └── images/
│ └── logo.png
├── run.py
└── config.py
app/static/css/style.css:
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
}
img {
max-width: 100px;
height: auto;
}
app/static/js/script.js:
document.addEventListener('DOMContentLoaded', (event) => {
console.log('JavaScript is loaded and running!');
});
app/templates/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home Page</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<h1>Welcome to My Flask App!</h1>
<img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>
app/routes.py:
from flask import Blueprint, render_template
bp = Blueprint('main', __name__)
@bp.route('/')
def index():
return render_template('index.html')
run.py:
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
app/init.py:
from flask import Flask
def create_app():
app = Flask(__name__)
app.config.from_object('config')
from .routes import bp as main_bp
app.register_blueprint(main_bp)
return app
Customizing the Static Folder Location
By default, Flask looks for the static folder in the application's root directory. However, you can customize this by setting the static_folder parameter when creating the Flask application.
from flask import Flask
app = Flask(__name__, static_folder='my_static_folder')
In this case, Flask will look for static files in the my_static_folder directory instead of the default static.
Summary
- Static Directory: Store your static assets in the
staticdirectory. Organize them into subdirectories likecss,js, andimagesfor better structure. - url_for Function: Use
url_for('static', filename='path/to/your/file')to generate URLs for static files in your templates. - Customizing: You can customize the location of the
staticfolder by passing a different path when creating the Flask app.
This setup allows you to effectively manage and serve static assets in your Flask applications, ensuring a clean and maintainable project structure.