Flask-Caching helps your web app remember responses so it can send them faster next time. This saves time and makes your app feel quicker.
Flask-Caching for response caching
from flask_caching import Cache cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/some') @cache.cached(timeout=60) def some_view(): # generate response return 'Hello, cached!'
Use @cache.cached(timeout=seconds) above a view function to cache its response.
Configure cache type in Cache(app, config={...}). 'simple' stores cache in memory.
from flask_caching import Cache cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') @cache.cached(timeout=30) def home(): return 'Welcome! This page is cached for 30 seconds.'
@app.route('/time') @cache.cached(timeout=10) def time(): import datetime return f"Current time: {datetime.datetime.now()}"
cache = Cache(app, config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp/cache'})
@app.route('/data')
@cache.cached(timeout=120)
def data():
return 'Data cached on disk for 2 minutes.'This Flask app shows the current time on the homepage. The response is cached for 15 seconds, so refreshing the page within 15 seconds shows the same time. After 15 seconds, the cache expires and the time updates.
from flask import Flask from flask_caching import Cache import datetime app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') @cache.cached(timeout=15) def index(): now = datetime.datetime.now() return f"Hello! Current time is {now.strftime('%H:%M:%S')}" if __name__ == '__main__': app.run(debug=True)
Cached responses are stored for the time you set in timeout. After that, the cache refreshes.
Use simple cache for development. For production, consider Redis or Memcached for better performance.
Remember to install Flask-Caching with pip install Flask-Caching before using it.
Flask-Caching stores responses to speed up your app.
Use @cache.cached(timeout=seconds) to cache view outputs.
Choose cache type based on your needs: simple, filesystem, Redis, etc.
Practice
Solution
Step 1: Understand Flask-Caching role
Flask-Caching is used to save the output of views temporarily.Step 2: Identify the benefit
Saving responses reduces processing time for repeated requests, speeding up the app.Final Answer:
To store responses temporarily to speed up repeated requests -> Option CQuick Check:
Flask-Caching = Response speedup [OK]
- Confusing caching with security features
- Thinking caching manages database or sessions
- Assuming caching permanently stores data
Solution
Step 1: Identify correct decorator name
The correct decorator is@cache.cachedwith a named argumenttimeout.Step 2: Check syntax for timeout
Timeout must be passed as a keyword argument:timeout=60.Final Answer:
@cache.cached(timeout=60)\ndef my_view():\n return 'Hello World' -> Option AQuick Check:
Decorator name and timeout keyword correct = A [OK]
- Using @cache.cache instead of @cache.cached
- Passing timeout as positional argument
- Omitting the timeout keyword
/time within 10 seconds?
from flask import Flask
from flask_caching import Cache
import time
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@app.route('/time')
@cache.cached(timeout=10)
def get_time():
return str(time.time())
# Assume the first request prints 1680000000.0Solution
Step 1: Understand caching behavior
The first call caches the response (timestamp) for 10 seconds.Step 2: Predict second request output within timeout
Within 10 seconds, the cached response is returned, so the timestamp stays the same.Final Answer:
The same timestamp 1680000000.0 -> Option DQuick Check:
Cached response repeats within timeout = D [OK]
- Expecting a new timestamp every request
- Assuming caching is disabled without error
- Confusing cache timeout with immediate refresh
from flask import Flask
from flask_caching import Cache
app = Flask(__name__)
cache = Cache()
@cache.cached(timeout=30)
@app.route('/')
def home():
return 'Welcome!'
cache.init_app(app)Solution
Step 1: Check decorator order
In Flask, @app.route must be the outer decorator, so it should be above @cache.cached.Step 2: Understand decorator stacking
Incorrect order causes the route not to register properly, breaking caching behavior.Final Answer:
The order of decorators is incorrect; @app.route should be above @cache.cached -> Option AQuick Check:
Decorator order matters = B [OK]
- Swapping decorator order
- Thinking cache.init_app must be before decorators
- Assuming no error with wrong decorator order
?user=admin. Which approach correctly applies Flask-Caching to cache only those responses?Solution
Step 1: Understand conditional caching
Flask-Caching'sunlessparameter skips caching when condition is True.Step 2: Apply condition for user param
Usingunless=lambda: request.args.get('user') != 'admin'caches only when user is 'admin'.Final Answer:
Use @cache.cached(timeout=30, unless=lambda: request.args.get('user') != 'admin') -> Option BQuick Check:
Conditional caching uses unless param = A [OK]
- Using query_string=True without filtering user
- Trying to cache manually inside view
- Using memoize without conditions
Ready to prove it?
Pass the test and this pattern moves unknown
