Cache Inspection#
Here are some ways to get additional information out of the cache session, backend, and responses:
Response Details#
The following attributes are available on responses:
from_cache
: indicates if the response came from the cachecache_key
: The unique identifier used to match the request to the response (see Request Matching for details)created_at
:datetime
of when the cached response was created or last updatedexpires
:datetime
after which the cached response will expire (see Expiration for details)is_expired
: indicates if the cached response is expired (if, for example, an old response was returned due to a request error)
Cache Contents#
Checking for responses#
Use BaseCache.contains()
to check if a given request is cached.
Check if a specific URL is cached:
>>> print(session.cache.contains(url='https://httpbin.org/get'))
To match additional request values (parameters, headers, etc), you can pass a
Request
object instead:
>>> from requests import Request
>>> request = Request('GET', 'https://httpbin.org/get', params={'k': 'v'})
>>> print(session.cache.contains(request=request))
You can also check for a specific cache key:
>>> print(session.cache.contains('d1e666e9fdfb3f86'))
Filtering responses#
Use BaseCache.filter()
to get responses with optional filters. By default, it returns all
responses except any invalid ones that would raise an exception:
>>> for response in session.cache.filter():
>>> print(response)
Get unexpired responses:
>>> for response in session.cache.filter(expired=False):
>>> print(response)
Get keys for only expired responses:
>>> expired_responses = session.cache.filter(valid=False, expired=True)
>>> keys = [response.cache_key for response in expired_responses]
Deleting responses#
Use BaseCache.delete()
to manually delete responses. See Manual Removal for
examples.
Response URLs#
You can use BaseCache.urls()
to see all URLs currently in the cache:
>>> session = CachedSession()
>>> print(session.cache.urls())
['https://httpbin.org/get', 'https://httpbin.org/stream/100']
Other response details#
If needed, you can access all responses via CachedSession.cache.responses
, which is a dict-like
interface to the cache backend, where:
Keys are cache keys (a hash of matched request information)
Values are
CachedResponse
objects
For example, if you wanted to see URLs only for POST
requests:
>>> post_urls = [
... response.url for response in session.cache.responses.values()
... if response.request.method == 'POST'
... ]