0
0
Flaskframework~30 mins

Static file optimization in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Static File Optimization in Flask
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use the standard Python block if __name__ == '__main__': to run app.run(debug=True).