6
6
from abc import ABC , abstractmethod
7
7
from enum import Enum
8
8
from types import TracebackType
9
- from typing import Callable , Generic , List , Optional , Set , TYPE_CHECKING , Type , TypeVar
9
+ from typing import Any , Callable , Generic , List , Optional , Set , TYPE_CHECKING , Type , TypeVar
10
10
11
11
from aiocache .serializers import StringSerializer
12
12
13
13
if TYPE_CHECKING : # pragma: no cover
14
14
from aiocache .plugins import BasePlugin
15
15
from aiocache .serializers import BaseSerializer
16
16
17
+ CacheKeyType = TypeVar ("CacheKeyType" )
18
+ CacheValueType = TypeVar ("CacheValueType" )
19
+
17
20
18
21
logger = logging .getLogger (__name__ )
19
22
20
23
SENTINEL = object ()
21
- CacheKeyType = TypeVar ("CacheKeyType" )
22
24
23
25
24
26
class API :
@@ -93,7 +95,7 @@ async def _plugins(self, *args, **kwargs):
93
95
return _plugins
94
96
95
97
96
- class BaseCache (Generic [CacheKeyType ], ABC ):
98
+ class BaseCache (Generic [CacheKeyType , CacheValueType ], ABC ):
97
99
"""
98
100
Base class that agregates the common logic for the different caches that may exist. Cache
99
101
related available options are:
@@ -110,6 +112,8 @@ class BaseCache(Generic[CacheKeyType], ABC):
110
112
By default its 5. Use 0 or None if you want to disable it.
111
113
:param ttl: int the expiration time in seconds to use as a default in all operations of
112
114
the backend. It can be overriden in the specific calls.
115
+ :typeparam CacheKeyType: The type of the cache key (e.g., str, bytes).
116
+ :typeparam CacheValueType: The type of the cache value (e.g., str, int, custom object).
113
117
"""
114
118
115
119
NAME : str
@@ -152,16 +156,25 @@ def plugins(self, value):
152
156
@API .aiocache_enabled (fake_return = True )
153
157
@API .timeout
154
158
@API .plugins
155
- async def add (self , key , value , ttl = SENTINEL , dumps_fn = None , namespace = None , _conn = None ):
159
+ async def add (
160
+ self ,
161
+ key : CacheKeyType ,
162
+ value : CacheValueType ,
163
+ ttl = SENTINEL ,
164
+ dumps_fn : Optional [Callable [[CacheValueType ], Any ]] = None ,
165
+ namespace : Optional [str ] = None ,
166
+ _conn = None ,
167
+ ) -> bool :
156
168
"""
157
169
Stores the value in the given key with ttl if specified. Raises an error if the
158
170
key already exists.
159
171
160
- :param key: str
161
- :param value: obj
162
- :param ttl: int the expiration time in seconds. Due to memcached
163
- restrictions if you want compatibility use int. In case you
164
- need miliseconds, redis and memory support float ttls
172
+ :param key: CacheKeyType
173
+ :param value: CacheValueType
174
+ :param ttl: int the expiration time in seconds. Due to memcached restrictions.
175
+ If you want compatibility use int.
176
+ In case you need milliseconds,
177
+ redis and memory support float ttls
165
178
:param dumps_fn: callable alternative to use as dumps function
166
179
:param namespace: str alternative namespace to use
167
180
:param timeout: int or float in seconds specifying maximum timeout
@@ -188,17 +201,24 @@ async def _add(self, key, value, ttl, _conn=None):
188
201
@API .aiocache_enabled ()
189
202
@API .timeout
190
203
@API .plugins
191
- async def get (self , key , default = None , loads_fn = None , namespace = None , _conn = None ):
204
+ async def get (
205
+ self ,
206
+ key : CacheKeyType ,
207
+ default : Optional [CacheValueType ] = None ,
208
+ loads_fn : Optional [Callable [[Any ], CacheValueType ]] = None ,
209
+ namespace : Optional [str ] = None ,
210
+ _conn = None ,
211
+ ) -> Optional [CacheValueType ]:
192
212
"""
193
213
Get a value from the cache. Returns default if not found.
194
214
195
- :param key: str
196
- :param default: obj to return when key is not found
215
+ :param key: CacheKeyType
216
+ :param default: CacheValueType to return when key is not found
197
217
:param loads_fn: callable alternative to use as loads function
198
218
:param namespace: str alternative namespace to use
199
219
:param timeout: int or float in seconds specifying maximum timeout
200
220
for the operations to last
201
- :returns: obj loaded
221
+ :returns: CacheValueType loaded
202
222
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
203
223
"""
204
224
start = time .monotonic ()
@@ -222,16 +242,22 @@ async def _gets(self, key, encoding="utf-8", _conn=None):
222
242
@API .aiocache_enabled (fake_return = [])
223
243
@API .timeout
224
244
@API .plugins
225
- async def multi_get (self , keys , loads_fn = None , namespace = None , _conn = None ):
245
+ async def multi_get (
246
+ self ,
247
+ keys : List [CacheKeyType ],
248
+ loads_fn : Optional [Callable [[Any ], CacheValueType ]] = None ,
249
+ namespace : Optional [str ] = None ,
250
+ _conn = None ,
251
+ ) -> List [Optional [CacheValueType ]]:
226
252
"""
227
253
Get multiple values from the cache, values not found are Nones.
228
254
229
- :param keys: list of str
255
+ :param keys: list of CacheKeyType
230
256
:param loads_fn: callable alternative to use as loads function
231
257
:param namespace: str alternative namespace to use
232
258
:param timeout: int or float in seconds specifying maximum timeout
233
259
for the operations to last
234
- :returns: list of objs
260
+ :returns: list of CacheValueType
235
261
:raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
236
262
"""
237
263
start = time .monotonic ()
@@ -262,13 +288,20 @@ async def _multi_get(self, keys, encoding, _conn=None):
262
288
@API .timeout
263
289
@API .plugins
264
290
async def set (
265
- self , key , value , ttl = SENTINEL , dumps_fn = None , namespace = None , _cas_token = None , _conn = None
266
- ):
291
+ self ,
292
+ key : CacheKeyType ,
293
+ value : CacheValueType ,
294
+ ttl = SENTINEL ,
295
+ dumps_fn : Optional [Callable [[CacheValueType ], Any ]] = None ,
296
+ namespace : Optional [str ] = None ,
297
+ _cas_token = None ,
298
+ _conn = None ,
299
+ ) -> bool :
267
300
"""
268
301
Stores the value in the given key with ttl if specified
269
302
270
- :param key: str
271
- :param value: obj
303
+ :param key: CacheKeyType
304
+ :param value: CacheValueType
272
305
:param ttl: int the expiration time in seconds. Due to memcached
273
306
restrictions if you want compatibility use int. In case you
274
307
need miliseconds, redis and memory support float ttls
@@ -298,14 +331,22 @@ async def _set(self, key, value, ttl, _cas_token=None, _conn=None):
298
331
@API .aiocache_enabled (fake_return = True )
299
332
@API .timeout
300
333
@API .plugins
301
- async def multi_set (self , pairs , ttl = SENTINEL , dumps_fn = None , namespace = None , _conn = None ):
334
+ async def multi_set (
335
+ self ,
336
+ pairs : List [tuple [CacheKeyType , CacheValueType ]],
337
+ ttl = SENTINEL ,
338
+ dumps_fn : Optional [Callable [[CacheValueType ], Any ]] = None ,
339
+ namespace : Optional [str ] = None ,
340
+ _conn = None ,
341
+ ) -> bool :
302
342
"""
303
343
Stores multiple values in the given keys.
304
344
305
- :param pairs: list of two element iterables. First is key and second is value
306
- :param ttl: int the expiration time in seconds. Due to memcached
307
- restrictions if you want compatibility use int. In case you
308
- need miliseconds, redis and memory support float ttls
345
+ :param pairs: list of two element iterables. First is CacheKeyType
346
+ and second is CacheValueType
347
+ :param ttl: int the expiration time in seconds. Due to memcached restrictions.
348
+ If you want compatibility use int. In case you need milliseconds,
349
+ redis and memory support float ttls
309
350
:param dumps_fn: callable alternative to use as dumps function
310
351
:param namespace: str alternative namespace to use
311
352
:param timeout: int or float in seconds specifying maximum timeout
@@ -326,7 +367,7 @@ async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _c
326
367
"MULTI_SET %s %d (%.4f)s" ,
327
368
[key for key , value in tmp_pairs ],
328
369
len (tmp_pairs ),
329
- time .monotonic () - start ,
370
+ time .monotonic () - start
330
371
)
331
372
return True
332
373
0 commit comments