0
0
Flaskframework~30 mins

Response caching strategies in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Response caching strategies in Flask
📖 Scenario: You are building a simple Flask web app that shows the current time. To make the app faster and reduce server load, you want to add caching strategies to store and reuse responses for a short time.
🎯 Goal: Build a Flask app with a route /time that returns the current time. Add a caching mechanism that stores the response for 10 seconds so repeated requests within that time return the cached response instead of recalculating the time.
📋 What You'll Learn
Create a Flask app with a route /time
Add a cache dictionary to store cached responses
Set a cache timeout of 10 seconds
Implement logic to return cached response if valid
Return fresh response and update cache if expired
💡 Why This Matters
🌍 Real World
Caching responses in web apps improves speed and reduces server load by reusing data instead of recalculating it every time.
💼 Career
Understanding caching strategies is important for backend developers to optimize web app performance and scalability.
Progress0 / 4 steps
1
Set up Flask app and route
Import Flask and datetime. Create a Flask app called app. Define a route /time with a function get_time that returns the current time as a string using datetime.datetime.now().
Flask
Need a hint?

Use datetime.now().strftime('%Y-%m-%d %H:%M:%S') to format the current time as a string.

2
Add cache dictionary and timeout
Create a dictionary called cache to store cached responses. Create a variable cache_timeout and set it to 10 seconds.
Flask
Need a hint?

Use a simple dictionary cache = {} and set cache_timeout = 10.

3
Implement caching logic in route
Inside get_time, import time. Check if 'time' key exists in cache and if the cached timestamp is within cache_timeout. If valid, return the cached response. Otherwise, get the current time string, store it in cache['time'] with the current timestamp, and return it.
Flask
Need a hint?

Use time.time() to get current timestamp. Store tuple of (response, timestamp) in cache.

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

This block runs the Flask app when you run the script directly.