|
1 | 1 | import logging |
2 | 2 | import time |
3 | | -from typing import Any, Callable, Optional, TYPE_CHECKING, List |
| 3 | +from typing import Any, Callable, List, Optional, Self, TYPE_CHECKING |
4 | 4 |
|
5 | 5 | from glide import ( |
6 | 6 | ConditionalChange, |
|
24 | 24 |
|
25 | 25 |
|
26 | 26 | class ValkeyBackend(BaseCache[str]): |
27 | | - def __init__( |
28 | | - self, |
29 | | - client: GlideClient, |
30 | | - **kwargs, |
31 | | - ): |
32 | | - super().__init__(**kwargs) |
33 | | - |
34 | | - self.client = client |
35 | | - |
36 | 27 | async def _get(self, key, encoding="utf-8", _conn=None): |
37 | 28 | value = await self.client.get(key) |
38 | 29 | if encoding is None or value is None: |
@@ -203,31 +194,33 @@ class ValkeyCache(ValkeyBackend): |
203 | 194 |
|
204 | 195 | def __init__( |
205 | 196 | self, |
206 | | - client: Optional[GlideClient] = None, |
207 | 197 | serializer: Optional["BaseSerializer"] = None, |
208 | 198 | namespace: str = "", |
209 | 199 | key_builder: Callable[[str, str], str] = lambda k, ns: f"{ns}:{k}" if ns else k, |
210 | | - backend: type[GlideClient] = GlideClient, |
211 | 200 | config: GlideClientConfiguration = None, |
212 | 201 | **kwargs: Any, |
213 | 202 | ): |
214 | 203 | super().__init__( |
215 | | - client=client, |
216 | 204 | serializer=serializer or JsonSerializer(), |
217 | 205 | namespace=namespace, |
218 | 206 | key_builder=key_builder, |
219 | 207 | **kwargs, |
220 | 208 | ) |
221 | | - self.backend = backend |
222 | 209 | self.config = config |
223 | 210 |
|
224 | | - async def __aenter__(self): |
| 211 | + async def __aenter__(self) -> Self: |
225 | 212 | if not self.config: |
226 | 213 | raise AttributeError("Configuration must be provided for context manager") |
227 | | - self.client = await self.backend.create(config=self.config) |
| 214 | + self.client = await self._connect(self.config) |
228 | 215 | return self |
229 | 216 |
|
230 | | - async def __aexit__(self, *args, **kwargs): |
| 217 | + async def __aexit__(self, *args, **kwargs) -> None: |
| 218 | + await self._disconnect() |
| 219 | + |
| 220 | + async def _connect(self, config: GlideClientConfiguration) -> GlideClient: |
| 221 | + return await GlideClient.create(config=config) |
| 222 | + |
| 223 | + async def _disconnect(self) -> None: |
231 | 224 | await self.client.close() |
232 | 225 |
|
233 | 226 | @classmethod |
|
0 commit comments