0
0
Flaskframework~30 mins

Flask-Caching for response caching - Mini Project: Build & Apply

Choose your learning style9 modes available
Flask-Caching for response caching
📖 Scenario: You are building a simple Flask web app that shows the current time. To make it faster and reduce server load, you want to cache the response for 10 seconds so repeated visits within that time show the cached time instead of recalculating.
🎯 Goal: Create a Flask app with a route /time that returns the current time. Use Flask-Caching to cache the response for 10 seconds.
📋 What You'll Learn
Create a Flask app instance named app
Set up Flask-Caching with a simple cache type
Create a route /time that returns the current time as a string
Cache the /time route response for 10 seconds using Flask-Caching
💡 Why This Matters
🌍 Real World
Caching responses in web apps improves speed and reduces server load, especially for data that doesn't change often.
💼 Career
Many web developer roles require knowledge of caching techniques to optimize app performance and scalability.
Progress0 / 4 steps
1
Set up the Flask app and import modules
Import Flask from flask and create a Flask app instance called app.
Flask
Need a hint?

Use app = Flask(__name__) to create the app instance.

2
Configure Flask-Caching
Import Cache from flask_caching. Create a Cache instance called cache and initialize it with app using the simple cache type.
Flask
Need a hint?

Use Cache(app, config={'CACHE_TYPE': 'SimpleCache'}) to set up caching.

3
Create the /time route with caching
Import datetime from datetime. Create a route /time using @app.route('/time'). Use @cache.cached(timeout=10) decorator to cache the response for 10 seconds. Inside the function time(), return the current time as a string using datetime.now().strftime('%H:%M:%S').
Flask
Need a hint?

Use @cache.cached(timeout=10) above the route function to cache the response for 10 seconds.

4
Add the app run block
Add the standard Flask app run block: if __name__ == '__main__': and inside it call app.run(debug=True).
Flask
Need a hint?

This block runs the app when you execute the script directly.