API Reference#
This section covers all the public interfaces of requests-cache.
Sessions#
- class requests_cache.session.CachedSession(cache_name='http_cache', backend=None, expire_after=- 1, urls_expire_after=None, allowable_codes=(200,), allowable_methods=('GET', 'HEAD'), filter_fn=None, old_data_on_error=False, cache_control=False, **kwargs)[source]#
Bases:
requests_cache.session.CacheMixin,requests.sessions.SessionClass that extends
requests.Sessionwith caching features.See individual
backend classesfor additional backend-specific arguments. Also see User Guide for more details and examples on how the following arguments affect cache behavior.- Parameters
cache_name (
str) – Cache prefix or namespace, depending on backendbackend (
Union[str,BaseCache,Type[BaseCache],None]) – Cache backend name, class, or instance; name may be one of['sqlite', 'mongodb', 'gridfs', 'redis', 'dynamodb', 'memory'].expire_after (
Union[None,int,float,str,datetime,timedelta]) – Time after which cached items will expireurls_expire_after (
Optional[Dict[str,Union[None,int,float,str,datetime,timedelta]]]) – Expiration times to apply for different URL patternsallowable_codes (
Iterable[int]) – Only cache responses with one of these codesallowable_methods (
Iterable[str]) – Cache only responses for one of these HTTP methodsinclude_get_headers – Make request headers part of the cache key
ignored_parameters – List of request parameters to be excluded from the cache key
filter_fn (
Optional[Callable]) – function that takes aaiohttp.ClientResponseobject and returns a boolean indicating whether or not that response should be cached. Will be applied to both new and previously cached responses.old_data_on_error (
bool) – Return stale cache data if a new request raises an exceptioncache_control (
bool) – Use Cache-Control request and response headers
- cache_disabled()#
Context manager for temporary disabling the cache
Warning
This method is not thread-safe.
Example
>>> s = CachedSession() >>> with s.cache_disabled(): ... s.get('http://httpbin.org/ip')
- remove_expired_responses(expire_after=None)#
Remove expired responses from the cache, optionally with revalidation
- request(method, url, params=None, data=None, json=None, expire_after=None, **kwargs)#
This method prepares and sends a request while automatically performing any necessary caching operations. This will be called by any other method-specific
requestsfunctions (get, post, etc.). This does not include prepared requests, which will still be cached viasend().See
requests.Session.request()for parameters. Additional parameters:- Parameters
expire_after (
Union[None,int,float,str,datetime,timedelta]) – Expiration time to set only for this request; see details below. OverridesCachedSession.expire_after. Accepts all the same values asCachedSession.expire_afterexcept forNone; use-1to disable expiration on a per-request basis.- Return type
- Returns
Either a new or cached response
Order of operations: For reference, a request will pass through the following methods:
requests.get()/requests.Session.get()or other method-specific functions (optional)requests.Session.send()(if not previously cached)BaseCache.save_response()(if not previously cached)
- class requests_cache.session.CacheMixin(cache_name='http_cache', backend=None, expire_after=- 1, urls_expire_after=None, allowable_codes=(200,), allowable_methods=('GET', 'HEAD'), filter_fn=None, old_data_on_error=False, cache_control=False, **kwargs)[source]#
Mixin class that extends
requests.Sessionwith caching features. SeeCachedSessionfor usage information.
Patching#
Utilities for patching requests.
Warning
These functions are not thread-safe. Use CachedSession directly if you
want to use caching in a multi-threaded environment.
- requests_cache.patcher.disabled()[source]#
Context manager for temporarily disabling caching for all
requestsfunctionsExample
>>> with requests_cache.disabled(): ... requests.get('http://httpbin.org/get')
- requests_cache.patcher.enabled(*args, **kwargs)[source]#
Context manager for temporarily enabling caching for all
requestsfunctionsAccepts the same arguments as
install_cache().Example
>>> with requests_cache.enabled('cache_db'): ... requests.get('http://httpbin.org/get')
- requests_cache.patcher.get_cache()[source]#
Get the internal cache object from the currently installed
CachedSession(if any)
- requests_cache.patcher.install_cache(cache_name='http_cache', backend=None, expire_after=-1, urls_expire_after=None, allowable_codes=(200, ), allowable_methods=('GET', 'HEAD'), filter_fn=None, old_data_on_error=False, session_factory=<class 'requests_cache.session.CachedSession'>, **kwargs)[source]#
Install the cache for all
requestsfunctions by monkey-patchingrequests.SessionExample
>>> requests_cache.install_cache('demo_cache')
Accepts all the same parameters as
CachedSession. Additional parameters:- Parameters
session_factory (
Type[Session]) – Session class to use. It must inherit from eitherCachedSessionorCacheMixin
- requests_cache.patcher.is_installed()[source]#
Indicate whether or not requests-cache is currently installed
- Return type
- requests_cache.patcher.remove_expired_responses(expire_after=None)[source]#
Remove expired responses from the cache, optionally with revalidation
- requests_cache.patcher.uninstall_cache()[source]#
Disable the cache by restoring the original
requests.Session