Bird
Raised Fist0
Flaskframework~20 mins

Response caching strategies in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Response Caching Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Flask route with cache control?

Consider this Flask route that sets cache headers:

from flask import Flask, make_response
app = Flask(__name__)

@app.route('/data')
def data():
    response = make_response('Hello World')
    response.headers['Cache-Control'] = 'public, max-age=60'
    return response

What will the browser do with the response?

Flask
from flask import Flask, make_response
app = Flask(__name__)

@app.route('/data')
def data():
    response = make_response('Hello World')
    response.headers['Cache-Control'] = 'public, max-age=60'
    return response
AThe browser does not cache the response at all.
BThe browser caches the response for 60 seconds and shares it with other users.
CThe browser caches the response but only for the current user session.
DThe browser caches the response indefinitely until manually cleared.
Attempts:
2 left
💡 Hint

Look at the meaning of 'public' and 'max-age' in Cache-Control headers.

❓ state_output
intermediate
2:00remaining
What is the cache behavior of this Flask route using @cache.cached?

Given this Flask route using Flask-Caching:

from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache'})

@app.route('/time')
@cache.cached(timeout=30)
def get_time():
    import time
    return str(time.time())

What happens when you call /time multiple times within 30 seconds?

Flask
from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache'})

@app.route('/time')
@cache.cached(timeout=30)
def get_time():
    import time
    return str(time.time())
AThe first call computes time; subsequent calls within 30 seconds return the cached time string.
BEach call computes a new time string regardless of caching.
CThe cache is ignored because SimpleCache does not support timeout.
DThe cache stores the time but expires immediately, so no caching occurs.
Attempts:
2 left
💡 Hint

Think about what @cache.cached with timeout does.

📝 Syntax
advanced
2:00remaining
Which option correctly sets a Flask response to never cache?

Which code snippet correctly sets HTTP headers to prevent caching of a Flask response?

Aresponse.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
Bresponse.headers['Cache-Control'] = 'public, max-age=0'
Cresponse.headers['Cache-Control'] = 'private, max-age=60'
Dresponse.headers['Cache-Control'] = 'max-age=3600, public'
Attempts:
2 left
💡 Hint

Look for headers that explicitly prevent caching.

🔧 Debug
advanced
2:00remaining
Why does this Flask cache not work as expected?

Consider this Flask route using Flask-Caching:

from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'NullCache'})

@app.route('/data')
@cache.cached(timeout=60)
def data():
    return 'Cached Data'

Why does caching not occur?

Flask
from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'NullCache'})

@app.route('/data')
@cache.cached(timeout=60)
def data():
    return 'Cached Data'
AThe timeout value is too low to cache anything.
BThe decorator @cache.cached is used incorrectly and does not cache.
CNullCache disables caching, so no data is stored or reused.
DFlask-Caching requires a Redis backend to cache data.
Attempts:
2 left
💡 Hint

Check the meaning of 'NullCache' in Flask-Caching.

🧠 Conceptual
expert
3:00remaining
Which caching strategy best suits dynamic user-specific content in Flask?

You have a Flask app serving user dashboards with personalized data that changes frequently. Which caching strategy is best to improve performance without showing wrong data?

ADisable all caching to ensure fresh data every request.
BSet Cache-Control to 'public, max-age=300' so all users share cached dashboards.
CUse client-side caching only with 'private, max-age=600' headers.
DUse server-side cache keyed by user ID to store each user's dashboard data separately.
Attempts:
2 left
💡 Hint

Think about caching personalized data safely.

Practice

(1/5)
1. What is the main purpose of response caching in a Flask application?
easy
A. To increase the size of the response data
B. To save server work and speed up response times
C. To make the server run slower intentionally
D. To disable user access temporarily

Solution

  1. Step 1: Understand response caching

    Response caching stores the output of a request so the server doesn't have to recompute it every time.
  2. Step 2: Identify the benefit

    This reduces server work and makes the app respond faster to repeated requests.
  3. Final Answer:

    To save server work and speed up response times -> Option B
  4. Quick Check:

    Response caching = save work & speed up [OK]
Hint: Caching speeds up responses by saving work [OK]
Common Mistakes:
  • Thinking caching increases response size
  • Believing caching slows down the server
  • Confusing caching with access control
2. Which of the following is the correct way to cache a Flask route response for 60 seconds using Flask-Caching?
easy
A. @cache.cache(60) def my_route(): return 'Hello'
B. @cache.cache(timeout=60) def my_route(): return 'Hello'
C. @cache.cached(timeout=60) def my_route(): return 'Hello'
D. @cached(60) def my_route(): return 'Hello'

Solution

  1. Step 1: Recall Flask-Caching decorator syntax

    The correct decorator is @cache.cached with a named argument timeout=60 to set cache duration.
  2. Step 2: Check each option

    @cache.cached(timeout=60) def my_route(): return 'Hello' uses correct decorator and syntax. Options A and B use cache.cache which is invalid. @cached(60) def my_route(): return 'Hello' misses the cache. instance prefix.
  3. Final Answer:

    @cache.cached(timeout=60) def my_route(): return 'Hello' -> Option C
  4. Quick Check:

    Use @cache.cached(timeout=seconds) [OK]
Hint: Use @cache.cached with timeout= seconds [OK]
Common Mistakes:
  • Using @cache.cache instead of @cache.cached
  • Omitting the cache. prefix (@cached instead of @cache.cached)
  • Using positional timeout argument
3. Given the code below, what will be printed on the second call to get_data() within 30 seconds?
@cache.cached(timeout=30)
def get_data():
    print('Fetching data...')
    return 'Data'
medium
A. Data
B. Fetching data...\nData
C. Fetching data...
D. Error: cache not found

Solution

  1. Step 1: Understand caching effect on function calls

    The first call runs the function, prints 'Fetching data...', and caches the return 'Data'.
  2. Step 2: Analyze second call within timeout

    Within 30 seconds, the cached result is returned directly, so the print statement does not run again.
  3. Final Answer:

    Data -> Option A
  4. Quick Check:

    Cached call skips print, returns cached 'Data' [OK]
Hint: Cached calls skip function body, return saved result [OK]
Common Mistakes:
  • Expecting print output on every call
  • Confusing cached return with function execution
  • Assuming cache misses cause errors
4. Identify the error in this Flask caching code snippet:
@cache.cached(timeout=60)
def index():
    return render_template('index.html')

# Later in code
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
medium
A. render_template cannot be cached
B. Timeout value must be a string, not integer
C. CACHE_TYPE 'simple' is invalid
D. Cache instance is created after using @cache.cached decorator

Solution

  1. Step 1: Check order of cache setup and usage

    The decorator @cache.cached uses the cache object, but it is created after the function definition, so cache is undefined at decoration time.
  2. Step 2: Validate other options

    Timeout as integer is valid. render_template output can be cached. 'simple' cache type is valid for development.
  3. Final Answer:

    Cache instance is created after using @cache.cached decorator -> Option D
  4. Quick Check:

    Define cache before using decorators [OK]
Hint: Create cache before decorating routes [OK]
Common Mistakes:
  • Defining cache after using it in decorators
  • Thinking timeout must be string
  • Believing templates can't be cached
5. You want to cache different responses for a Flask route based on the logged-in user ID. Which caching strategy should you use to ensure each user gets their own cached response?
hard
A. Use @cache.cached(timeout=60, key_prefix=lambda: f'user_{current_user.id}')
B. Use @cache.cached(timeout=60, key_prefix=lambda: request.args)
C. Use @cache.cached(timeout=60, key_prefix=lambda: request.path)
D. Use @cache.cached(timeout=60) without key_prefix

Solution

  1. Step 1: Understand caching by key prefix

    The cache stores responses by keys. To cache per user, the key must include the user ID.
  2. Step 2: Evaluate options for key prefix

    Use @cache.cached(timeout=60, key_prefix=lambda: f'user_{current_user.id}') uses a lambda returning a string with the current user's ID, ensuring unique cache per user. Use @cache.cached(timeout=60, key_prefix=lambda: request.path) uses request path only, same for all users. Use @cache.cached(timeout=60, key_prefix=lambda: request.args) uses request arguments, which may not include user ID. Use @cache.cached(timeout=60) without key_prefix uses default key, same for all users.
  3. Final Answer:

    Use @cache.cached(timeout=60, key_prefix=lambda: f'user_{current_user.id}') -> Option A
  4. Quick Check:

    Cache key must include user ID for per-user caching [OK]
Hint: Include user ID in cache key prefix [OK]
Common Mistakes:
  • Using only request path for cache key
  • Ignoring user-specific cache needs
  • Not using key_prefix for per-user caching
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard