0
# Core Cache Operations
1
2
Direct cache manipulation methods that provide fine-grained control over cached data. These operations form the foundation for all Flask-Caching functionality and allow direct interaction with the underlying cache backend.
3
4
## Capabilities
5
6
### Getting Values
7
8
Retrieve cached values by key. Returns None if the key doesn't exist or has expired.
9
10
```python { .api }
11
def get(key: str) -> Any:
12
"""
13
Retrieve a value from the cache.
14
15
Parameters:
16
- key: Cache key to retrieve
17
18
Returns:
19
The cached value or None if not found
20
"""
21
```
22
23
**Usage:**
24
```python
25
# Get a single value
26
user_data = cache.get('user:123')
27
if user_data is None:
28
user_data = fetch_user_from_database(123)
29
cache.set('user:123', user_data, timeout=300)
30
31
# Get with fallback handling
32
settings = cache.get('app_settings')
33
if settings is None:
34
settings = {}
35
```
36
37
### Setting Values
38
39
Store values in the cache with optional timeout. Returns True if successful, False otherwise.
40
41
```python { .api }
42
def set(key: str, value: Any, timeout: Optional[int] = None) -> Optional[bool]:
43
"""
44
Store a value in the cache.
45
46
Parameters:
47
- key: Cache key to store under
48
- value: Value to cache (must be serializable)
49
- timeout: Expiration time in seconds (None uses default timeout)
50
51
Returns:
52
True if successful, False otherwise, None for some backends
53
"""
54
```
55
56
**Usage:**
57
```python
58
# Set with default timeout
59
cache.set('user:123', user_data)
60
61
# Set with custom timeout (5 minutes)
62
cache.set('temp_token', token, timeout=300)
63
64
# Set with no expiration
65
cache.set('permanent_config', config, timeout=0)
66
```
67
68
### Checking Existence
69
70
Check if a key exists in the cache without retrieving its value.
71
72
```python { .api }
73
def has(key: str) -> bool:
74
"""
75
Check if a key exists in the cache.
76
77
Parameters:
78
- key: Cache key to check
79
80
Returns:
81
True if key exists, False otherwise
82
"""
83
```
84
85
**Usage:**
86
```python
87
if cache.has('user:123'):
88
user_data = cache.get('user:123')
89
else:
90
user_data = fetch_user_from_database(123)
91
cache.set('user:123', user_data)
92
```
93
94
### Adding Values
95
96
Add a value only if the key doesn't already exist. Atomic operation that prevents overwriting existing values.
97
98
```python { .api }
99
def add(key: str, value: Any, timeout: Optional[int] = None) -> bool:
100
"""
101
Add a value to the cache only if key doesn't exist.
102
103
Parameters:
104
- key: Cache key to store under
105
- value: Value to cache
106
- timeout: Expiration time in seconds
107
108
Returns:
109
True if value was added, False if key already exists
110
"""
111
```
112
113
**Usage:**
114
```python
115
# Atomic cache-or-compute pattern
116
if cache.add('computation_result:abc', None, timeout=3600):
117
# We got the lock, compute the result
118
result = expensive_computation('abc')
119
cache.set('computation_result:abc', result, timeout=3600)
120
else:
121
# Another process is computing, wait and get result
122
result = cache.get('computation_result:abc')
123
```
124
125
### Deleting Values
126
127
Remove specific keys or multiple keys from the cache.
128
129
```python { .api }
130
def delete(key: str) -> bool:
131
"""
132
Delete a key from the cache.
133
134
Parameters:
135
- key: Cache key to delete
136
137
Returns:
138
True if key was deleted, False if key didn't exist
139
"""
140
141
def delete_many(*keys) -> List[str]:
142
"""
143
Delete multiple keys from the cache.
144
145
Parameters:
146
- keys: Variable number of cache keys to delete
147
148
Returns:
149
List of successfully deleted keys
150
"""
151
```
152
153
**Usage:**
154
```python
155
# Delete single key
156
cache.delete('user:123')
157
158
# Delete multiple keys
159
deleted_keys = cache.delete_many('user:123', 'user:456', 'user:789')
160
print(f"Deleted {len(deleted_keys)} keys")
161
```
162
163
### Clearing Cache
164
165
Remove all cached values. Use with caution in production environments.
166
167
```python { .api }
168
def clear() -> bool:
169
"""
170
Clear all cached values.
171
172
Returns:
173
True if cache was cleared successfully
174
"""
175
```
176
177
**Usage:**
178
```python
179
# Clear all cached data
180
cache.clear()
181
```
182
183
### Bulk Operations
184
185
Efficient operations for working with multiple cache keys simultaneously.
186
187
```python { .api }
188
def get_many(*keys) -> List[Any]:
189
"""
190
Get multiple values from cache.
191
192
Parameters:
193
- keys: Variable number of cache keys
194
195
Returns:
196
List of values in same order as keys (None for missing keys)
197
"""
198
199
def set_many(mapping: Dict[str, Any], timeout: Optional[int] = None) -> List[Any]:
200
"""
201
Set multiple key-value pairs.
202
203
Parameters:
204
- mapping: Dictionary of key-value pairs to cache
205
- timeout: Expiration time for all keys
206
207
Returns:
208
List of results for each set operation
209
"""
210
211
def get_dict(*keys) -> Dict[str, Any]:
212
"""
213
Get multiple values as a dictionary.
214
215
Parameters:
216
- keys: Variable number of cache keys
217
218
Returns:
219
Dictionary mapping keys to values (excludes missing keys)
220
"""
221
```
222
223
**Usage:**
224
```python
225
# Bulk get operations
226
user_ids = ['user:123', 'user:456', 'user:789']
227
user_data_list = cache.get_many(*user_ids)
228
user_data_dict = cache.get_dict(*user_ids)
229
230
# Bulk set operations
231
cache.set_many({
232
'user:123': user_123_data,
233
'user:456': user_456_data,
234
'user:789': user_789_data
235
}, timeout=300)
236
```
237
238
### Redis-Specific Operations
239
240
Additional operations available when using Redis backends.
241
242
```python { .api }
243
def unlink(*keys) -> List[str]:
244
"""
245
Redis UNLINK command for non-blocking key deletion.
246
Falls back to delete_many for non-Redis backends.
247
248
Parameters:
249
- keys: Variable number of cache keys to unlink
250
251
Returns:
252
List of successfully unlinked keys
253
"""
254
```
255
256
**Usage:**
257
```python
258
# Non-blocking deletion for large values (Redis only)
259
cache.unlink('large_dataset:processed', 'large_dataset:raw')
260
```