0
# Session-Based Caching
1
2
Session-based caching provides the primary interface for requests-cache, offering drop-in replacement for `requests.Session` with transparent caching capabilities. This approach gives you full control over cache settings and behavior while maintaining compatibility with existing requests-based code.
3
4
## Capabilities
5
6
### CachedSession
7
8
The main session class that extends `requests.Session` with caching features. Provides all standard HTTP methods (GET, POST, PUT, etc.) with automatic caching based on configurable policies.
9
10
```python { .api }
11
class CachedSession:
12
def __init__(
13
self,
14
cache_name: StrOrPath = 'http_cache',
15
backend: Optional[BackendSpecifier] = None,
16
serializer: Optional[SerializerType] = None,
17
expire_after: ExpirationTime = -1,
18
urls_expire_after: Optional[ExpirationPatterns] = None,
19
cache_control: bool = False,
20
allowable_codes: Iterable[int] = (200,),
21
allowable_methods: Iterable[str] = ('GET', 'HEAD'),
22
always_revalidate: bool = False,
23
ignored_parameters: Iterable[str] = None,
24
match_headers: Union[Iterable[str], bool] = False,
25
filter_fn: Optional[FilterCallback] = None,
26
key_fn: Optional[KeyCallback] = None,
27
stale_if_error: Union[bool, int] = False,
28
**kwargs
29
):
30
"""
31
Initialize cached session with caching features.
32
33
Parameters:
34
- cache_name: Cache path, prefix, or namespace depending on backend
35
- backend: Backend name ('sqlite', 'redis', 'mongodb', etc.) or instance
36
- serializer: Serializer name ('pickle', 'json', 'yaml', 'bson') or instance
37
- expire_after: Default expiration time for cached responses
38
- urls_expire_after: URL-specific expiration patterns
39
- cache_control: Use HTTP Cache-Control headers for expiration
40
- allowable_codes: Only cache responses with these status codes
41
- allowable_methods: Cache only these HTTP methods
42
- always_revalidate: Always validate cached responses with server
43
- ignored_parameters: Parameters to exclude from cache keys
44
- match_headers: Headers to include in cache keys
45
- filter_fn: Custom function to determine what responses to cache
46
- key_fn: Custom function for generating cache keys
47
- stale_if_error: Return stale responses on errors
48
"""
49
50
def get(self, url: str, params=None, **kwargs) -> AnyResponse: ...
51
def post(self, url: str, data=None, **kwargs) -> AnyResponse: ...
52
def put(self, url: str, data=None, **kwargs) -> AnyResponse: ...
53
def patch(self, url: str, data=None, **kwargs) -> AnyResponse: ...
54
def delete(self, url: str, **kwargs) -> AnyResponse: ...
55
def head(self, url: str, **kwargs) -> AnyResponse: ...
56
def options(self, url: str, **kwargs) -> AnyResponse: ...
57
58
def request(
59
self,
60
method: str,
61
url: str,
62
headers: Optional[MutableMapping[str, str]] = None,
63
expire_after: ExpirationTime = None,
64
only_if_cached: bool = False,
65
refresh: bool = False,
66
force_refresh: bool = False,
67
**kwargs
68
) -> AnyResponse:
69
"""
70
Send HTTP request with caching.
71
72
Parameters:
73
- method: HTTP method
74
- url: Request URL
75
- headers: Request headers
76
- expire_after: Override default expiration for this request
77
- only_if_cached: Return 504 if not cached instead of making request
78
- refresh: Revalidate cached response before use
79
- force_refresh: Always make new request, overwrite cache
80
- **kwargs: Additional arguments passed to requests
81
"""
82
83
def send(
84
self,
85
request: PreparedRequest,
86
expire_after: ExpirationTime = None,
87
only_if_cached: bool = False,
88
refresh: bool = False,
89
force_refresh: bool = False,
90
**kwargs
91
) -> AnyResponse:
92
"""Send prepared request with caching."""
93
94
@property
95
def settings(self) -> CacheSettings:
96
"""Current cache settings."""
97
98
@settings.setter
99
def settings(self, value: CacheSettings): ...
100
101
@property
102
def expire_after(self) -> ExpirationTime:
103
"""Default expiration time (backwards compatibility)."""
104
105
@expire_after.setter
106
def expire_after(self, value: ExpirationTime): ...
107
108
def cache_disabled(self):
109
"""Context manager to temporarily disable caching."""
110
111
def close(self):
112
"""Close session and backend connections."""
113
```
114
115
#### Usage Examples
116
117
Basic usage with default SQLite backend:
118
119
```python
120
from requests_cache import CachedSession
121
122
# Create session with default settings
123
session = CachedSession('my_cache')
124
response = session.get('https://api.example.com/data')
125
print(f"From cache: {response.from_cache}")
126
127
# Same request will be served from cache
128
response2 = session.get('https://api.example.com/data')
129
print(f"From cache: {response2.from_cache}") # True
130
```
131
132
Advanced configuration:
133
134
```python
135
from requests_cache import CachedSession
136
from datetime import timedelta
137
138
session = CachedSession(
139
cache_name='advanced_cache',
140
backend='redis',
141
expire_after=timedelta(hours=1),
142
urls_expire_after={
143
'*.example.com/api/data': timedelta(minutes=5),
144
'*.slow-api.com': timedelta(days=1),
145
},
146
allowable_codes=[200, 201, 404],
147
allowable_methods=['GET', 'POST'],
148
ignored_parameters=['api_key', 'session_id'],
149
cache_control=True,
150
stale_if_error=True
151
)
152
```
153
154
Per-request cache control:
155
156
```python
157
# Override expiration for specific request
158
response = session.get(
159
'https://api.example.com/data',
160
expire_after=300 # 5 minutes
161
)
162
163
# Force refresh (bypass cache)
164
response = session.get(
165
'https://api.example.com/data',
166
force_refresh=True
167
)
168
169
# Only return if cached
170
response = session.get(
171
'https://api.example.com/data',
172
only_if_cached=True
173
)
174
```
175
176
### CacheMixin
177
178
Mixin class that can add caching features to any existing `requests.Session` subclass or instance. Useful for integrating with custom session classes or third-party libraries.
179
180
```python { .api }
181
class CacheMixin:
182
def __init__(self, **kwargs):
183
"""Initialize mixin with cache settings."""
184
185
@classmethod
186
def wrap(cls, original_session: Session, **kwargs) -> 'CacheMixin':
187
"""
188
Add caching to existing Session while preserving settings.
189
190
Parameters:
191
- original_session: Session object to wrap
192
- **kwargs: Cache configuration options
193
194
Returns:
195
CacheMixin instance with original session settings
196
"""
197
198
def cache_disabled(self):
199
"""Context manager to temporarily disable caching."""
200
201
def close(self):
202
"""Close session and backend connections."""
203
```
204
205
#### Usage Examples
206
207
Wrapping an existing session:
208
209
```python
210
import requests
211
from requests_cache import CacheMixin
212
213
# Create and configure a regular session
214
original = requests.Session()
215
original.auth = ('username', 'password')
216
original.headers.update({'User-Agent': 'MyApp/1.0'})
217
218
# Add caching while preserving all settings
219
cached_session = CacheMixin.wrap(
220
original,
221
cache_name='wrapped_cache',
222
expire_after=3600
223
)
224
225
response = cached_session.get('https://api.example.com/data')
226
```
227
228
Using as a mixin with custom session class:
229
230
```python
231
from requests import Session
232
from requests_cache import CacheMixin
233
234
class CustomCachedSession(CacheMixin, Session):
235
def __init__(self, **cache_kwargs):
236
super().__init__(**cache_kwargs)
237
# Add custom session configuration
238
self.headers.update({'Accept': 'application/json'})
239
240
session = CustomCachedSession(
241
cache_name='custom_cache',
242
backend='filesystem'
243
)
244
```
245
246
### Cache Management
247
248
Additional session methods for managing cached data:
249
250
```python { .api }
251
# Through session.cache property
252
session.cache.clear() # Clear all cached responses
253
session.cache.delete(urls=['https://example.com']) # Delete specific URLs
254
session.cache.delete_expired() # Delete expired responses only
255
len(session.cache) # Get number of cached responses
256
```
257
258
## Types
259
260
```python { .api }
261
# Session-related types
262
AnyResponse = Union[OriginalResponse, CachedResponse]
263
MutableMapping = Dict[str, str] # For headers parameter
264
```