Consider a REST API cache that stores data with an expiration timestamp. Given the following code snippet, what will be the output?
import time cache = {'data': 'value', 'expires_at': time.time() + 2} # Wait 3 seconds to simulate delay time.sleep(3) if time.time() > cache['expires_at']: print('Cache expired') else: print('Cache valid')
Think about how the expiration time compares to the current time after the delay.
The cache expiration time is set 2 seconds ahead. After sleeping 3 seconds, the current time is greater than the expiration time, so the cache is expired.
In REST APIs, which HTTP header tells clients how long to keep a cached response before requesting it again?
It controls caching policies like max-age and no-cache.
The Cache-Control header specifies caching directives including expiration times for responses.
Look at this cache expiration code snippet. Why does the cache never expire?
import time cache = {'data': 'value', 'expires_at': time.time() + 5} # Check expiration if time.time() < cache['expires_at']: print('Cache expired') else: print('Cache valid')
Check the logic of the if condition comparing current time and expiration time.
The condition uses < instead of >, so it treats valid cache as expired and vice versa, causing wrong output.
Choose the correct Python code to set a cache expiration timestamp 10 seconds in the future.
Remember the correct function to get current time in seconds is time.time()
Option C correctly calls time.time() and adds 10 seconds. Option C sets expiration in the past. Option C uses a non-existent function time.now(). Option C uses time.time without parentheses, which is a function object, not a number.
Given this cache dictionary with expiration timestamps, how many items remain after removing expired entries?
import time cache = { 'a': {'value': 1, 'expires_at': time.time() + 5}, 'b': {'value': 2, 'expires_at': time.time() - 1}, 'c': {'value': 3, 'expires_at': time.time() + 10}, 'd': {'value': 4, 'expires_at': time.time() - 10} } # Remove expired now = time.time() cache = {k: v for k, v in cache.items() if v['expires_at'] > now} print(len(cache))
Check which items have expiration times greater than current time.
Only keys 'a' and 'c' have expiration times in the future, so 2 items remain after cleanup.