📖 Scenario: You are building a simple Flask web app that serves CSS and JavaScript files. To improve loading speed, you want to optimize how these static files are served.
🎯 Goal: Learn how to set up static files in Flask and configure caching headers to optimize their delivery.
📋 What You'll Learn
Create a Flask app with a static folder
Add a CSS file and a JavaScript file in the static folder
Configure Flask to serve static files with caching headers
Use the static files in a simple HTML template
💡 Why This Matters
🌍 Real World
Web apps often serve CSS and JavaScript files as static files. Optimizing their delivery improves user experience by loading pages faster.
💼 Career
Understanding static file optimization is important for web developers to build efficient and performant web applications.
Progress0 / 4 steps
1
Create Flask app and static files
Create a Flask app instance called app. Then create a folder named static and inside it create two files: style.css with the content body { background-color: #f0f0f0; } and script.js with the content console.log('Hello from script');.
Flask
Hint
Use Flask(__name__) to create the app. Static files go in the static folder.
2
Add configuration for static file caching
Add a configuration variable app.config['SEND_FILE_MAX_AGE_DEFAULT'] and set it to 31536000 (one year in seconds) to enable caching of static files.
Flask
Hint
Set app.config['SEND_FILE_MAX_AGE_DEFAULT'] to 31536000 to cache static files for one year.
3
Create a route to render HTML using static files
Create a route @app.route('/') with a function index() that returns a string of HTML. The HTML should include a <link> tag to load style.css and a <script> tag to load script.js using url_for('static', filename='style.css') and url_for('static', filename='script.js') respectively.
Flask
Hint
Use @app.route('/') and return HTML string with url_for('static', filename=...) for CSS and JS files.
4
Run the Flask app with debug mode
Add the code block if __name__ == '__main__': and inside it call app.run(debug=True) to run the Flask app in debug mode.
Flask
Hint
Use the standard Python block if __name__ == '__main__': to run app.run(debug=True).
Practice
(1/5)
1. What is the main purpose of static file optimization in a Flask web application?
easy
A. To disable caching of static files
B. To add more static files to the project
C. To make the website load faster by reducing file sizes
D. To change the content of static files dynamically
Solution
Step 1: Understand static file optimization
Static file optimization means making files like CSS, JS, and images smaller or faster to load.
Step 2: Identify the main goal
The goal is to reduce file sizes or improve delivery so the website loads faster for users.
Final Answer:
To make the website load faster by reducing file sizes -> Option C
Quick Check:
Optimization = faster loading [OK]
Hint: Optimization means making files smaller or faster [OK]
Common Mistakes:
Thinking optimization adds more files
Confusing dynamic content with static files
Believing optimization disables caching
2. Which Flask extension is commonly used to add compression for static files to optimize them?
easy
A. flask_sqlalchemy
B. flask_compress
C. flask_login
D. flask_migrate
Solution
Step 1: Identify Flask extensions for compression
Among Flask extensions, flask_compress is designed to compress responses including static files.
Step 2: Match extension to purpose
flask_sqlalchemy is for databases, flask_login for user sessions, and flask_migrate for database migrations, so they don't compress files.
Final Answer:
flask_compress -> Option B
Quick Check:
Compression extension = flask_compress [OK]
Hint: Compression in Flask? Think flask_compress [OK]
Common Mistakes:
Choosing database or login extensions by mistake
Confusing migration tools with compression
Not knowing Flask extensions' purposes
3. Given this Flask snippet using flask_compress:
from flask import Flask
from flask_compress import Compress
app = Flask(__name__)
Compress(app)
@app.route('/')
def home():
return app.send_static_file('style.css')
What happens when a browser requests /?
medium
A. The server sends style.css without compression
B. The server sends an HTML page instead of style.css
C. The server returns a 404 error
D. The server sends the compressed version of style.css
Solution
Step 1: Understand flask_compress effect
When flask_compress is initialized with the app, it compresses responses automatically if the client supports it.
Step 2: Analyze the route behavior
The route returns the static file 'style.css' using send_static_file. With compression enabled, this file is sent compressed.
Final Answer:
The server sends the compressed version of style.css -> Option D
Hint: flask_compress compresses all responses including static files [OK]
Common Mistakes:
Assuming static files are never compressed
Expecting a 404 error without reason
Thinking the route sends HTML by default
4. You added flask_compress to your Flask app but static files are not compressed. What is a likely cause?
medium
A. You forgot to call Compress(app) after creating the app
B. You used app.run() instead of app.start()
C. Static files cannot be compressed in Flask
D. You did not install Flask
Solution
Step 1: Check flask_compress setup
To enable compression, you must call Compress(app) after creating the Flask app instance.
Step 2: Eliminate other options
app.run() is correct to start Flask; static files can be compressed; Flask must be installed to run at all.
Final Answer:
You forgot to call Compress(app) after creating the app -> Option A
Quick Check:
Missing Compress(app) disables compression [OK]
Hint: Always call Compress(app) after app creation [OK]
Common Mistakes:
Confusing app.run() with app.start()
Thinking Flask can't compress static files
Ignoring extension initialization step
5. You want to optimize your Flask app's static files by compressing them and setting cache headers for better performance. Which code snippet correctly applies both optimizations?
hard
A. from flask import Flask, send_from_directory
from flask_compress import Compress
app = Flask(__name__)
Compress(app)
@app.route('/static/')
def static_files(filename):
response = send_from_directory('static', filename)
response.cache_control.max_age = 31536000 # 1 year
return response
B. from flask import Flask
app = Flask(__name__)
@app.route('/static/<filename>')
def static_files(filename):
return open(f'static/{filename}').read()
C. from flask import Flask
from flask_compress import Compress
app = Flask(__name__)
@app.route('/static/<filename>')
def static_files(filename):
return open(f'static/{filename}').read()
D. from flask import Flask, send_static_file
app = Flask(__name__)
@app.route('/static/<filename>')
def static_files(filename):
return send_static_file(filename)
Solution
Step 1: Enable compression with flask_compress
from flask import Flask, send_from_directory
from flask_compress import Compress
app = Flask(__name__)
Compress(app)
@app.route('/static/')
def static_files(filename):
response = send_from_directory('static', filename)
response.cache_control.max_age = 31536000 # 1 year
return response correctly imports and calls Compress(app) to enable compression.
Step 2: Set cache headers on static file response
from flask import Flask, send_from_directory
from flask_compress import Compress
app = Flask(__name__)
Compress(app)
@app.route('/static/')
def static_files(filename):
response = send_from_directory('static', filename)
response.cache_control.max_age = 31536000 # 1 year
return response sets cache_control.max_age to 1 year, which helps browsers cache files efficiently.
Step 3: Verify other options
Options B, C, and D do not enable compression or set cache headers properly, and B and C read files unsafely without response objects.
Final Answer:
Option A code snippet correctly compresses and caches static files -> Option A