database-wrapper-redis 0.2.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- database_wrapper_redis-0.2.5/PKG-INFO +74 -0
- database_wrapper_redis-0.2.5/README.md +37 -0
- database_wrapper_redis-0.2.5/database_wrapper_redis/__init__.py +45 -0
- database_wrapper_redis-0.2.5/database_wrapper_redis/connector.py +502 -0
- database_wrapper_redis-0.2.5/database_wrapper_redis/py.typed +0 -0
- database_wrapper_redis-0.2.5/database_wrapper_redis.egg-info/PKG-INFO +74 -0
- database_wrapper_redis-0.2.5/database_wrapper_redis.egg-info/SOURCES.txt +10 -0
- database_wrapper_redis-0.2.5/database_wrapper_redis.egg-info/dependency_links.txt +1 -0
- database_wrapper_redis-0.2.5/database_wrapper_redis.egg-info/requires.txt +2 -0
- database_wrapper_redis-0.2.5/database_wrapper_redis.egg-info/top_level.txt +1 -0
- database_wrapper_redis-0.2.5/pyproject.toml +51 -0
- database_wrapper_redis-0.2.5/setup.cfg +4 -0
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: database_wrapper_redis
|
|
3
|
+
Version: 0.2.5
|
|
4
|
+
Summary: database_wrapper for Redis database
|
|
5
|
+
Author-email: Gints Murans <gm@gm.lv>
|
|
6
|
+
License: GNU General Public License v3.0 (GPL-3.0)
|
|
7
|
+
Project-URL: Homepage, https://github.com/gintsmurans/py_database_wrapper
|
|
8
|
+
Project-URL: Documentation, https://github.com/gintsmurans/py_database_wrapper
|
|
9
|
+
Project-URL: Changes, https://github.com/gintsmurans/py_database_wrapper
|
|
10
|
+
Project-URL: Code, https://github.com/gintsmurans/py_database_wrapper
|
|
11
|
+
Project-URL: Issue Tracker, https://github.com/gintsmurans/py_database_wrapper/issues
|
|
12
|
+
Project-URL: Download, https://pypi.org/project/database_wrapper/
|
|
13
|
+
Keywords: database,wrapper,python,redis
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
|
17
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
18
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
19
|
+
Classifier: Operating System :: POSIX
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
27
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
28
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
29
|
+
Classifier: Topic :: Database
|
|
30
|
+
Classifier: Topic :: Database :: Front-Ends
|
|
31
|
+
Classifier: Topic :: Software Development
|
|
32
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
33
|
+
Requires-Python: >=3.8
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
Requires-Dist: database_wrapper==0.2.5
|
|
36
|
+
Requires-Dist: redis
|
|
37
|
+
|
|
38
|
+
# database_wrapper_redis
|
|
39
|
+
|
|
40
|
+
_Part of the `database_wrapper` package._
|
|
41
|
+
|
|
42
|
+
This python package is a database wrapper for [Redis](https://redis.io/).
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install database_wrapper[redis]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from database_wrapper_redis import RedisDBWithPoolAsync, RedisDB
|
|
54
|
+
|
|
55
|
+
db = RedisDBWithPoolAsync({
|
|
56
|
+
"hostname": "localhost",
|
|
57
|
+
"port": 3306,
|
|
58
|
+
"username": "root",
|
|
59
|
+
"password": "your_password",
|
|
60
|
+
"database": 0
|
|
61
|
+
})
|
|
62
|
+
await db.open()
|
|
63
|
+
try:
|
|
64
|
+
async with db as redis_con:
|
|
65
|
+
await redis_con.set("key", "value")
|
|
66
|
+
value = await redis_con.get("key")
|
|
67
|
+
print(value) # Output: b'value'
|
|
68
|
+
|
|
69
|
+
finally:
|
|
70
|
+
await db.close()
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Notes
|
|
74
|
+
No wrapper at this time, as redis is just a key-value store.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# database_wrapper_redis
|
|
2
|
+
|
|
3
|
+
_Part of the `database_wrapper` package._
|
|
4
|
+
|
|
5
|
+
This python package is a database wrapper for [Redis](https://redis.io/).
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install database_wrapper[redis]
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from database_wrapper_redis import RedisDBWithPoolAsync, RedisDB
|
|
17
|
+
|
|
18
|
+
db = RedisDBWithPoolAsync({
|
|
19
|
+
"hostname": "localhost",
|
|
20
|
+
"port": 3306,
|
|
21
|
+
"username": "root",
|
|
22
|
+
"password": "your_password",
|
|
23
|
+
"database": 0
|
|
24
|
+
})
|
|
25
|
+
await db.open()
|
|
26
|
+
try:
|
|
27
|
+
async with db as redis_con:
|
|
28
|
+
await redis_con.set("key", "value")
|
|
29
|
+
value = await redis_con.get("key")
|
|
30
|
+
print(value) # Output: b'value'
|
|
31
|
+
|
|
32
|
+
finally:
|
|
33
|
+
await db.close()
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Notes
|
|
37
|
+
No wrapper at this time, as redis is just a key-value store.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""
|
|
2
|
+
database_wrapper_redis package - PostgreSQL database wrapper
|
|
3
|
+
|
|
4
|
+
Part of the database_wrapper package
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# Copyright 2024 Gints Murans
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
|
|
11
|
+
from .connector import (
|
|
12
|
+
# Basics
|
|
13
|
+
RedisConfig,
|
|
14
|
+
# Connectors
|
|
15
|
+
RedisDB,
|
|
16
|
+
RedisDBAsync,
|
|
17
|
+
RedisDBWithPool,
|
|
18
|
+
RedisDBWithPoolAsync,
|
|
19
|
+
# Connection and Cursor types
|
|
20
|
+
RedisClient,
|
|
21
|
+
RedisClientAsync,
|
|
22
|
+
RedisConnection,
|
|
23
|
+
RedisConnectionAsync,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# Set the logger to a quiet default, can be enabled if needed
|
|
27
|
+
logger = logging.getLogger("database_wrapper_redis")
|
|
28
|
+
if logger.level == logging.NOTSET:
|
|
29
|
+
logger.setLevel(logging.WARNING)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
# Connectors
|
|
34
|
+
"RedisDB",
|
|
35
|
+
"RedisDBAsync",
|
|
36
|
+
"RedisDBWithPool",
|
|
37
|
+
"RedisDBWithPoolAsync",
|
|
38
|
+
# Connection and Cursor types
|
|
39
|
+
"RedisClient",
|
|
40
|
+
"RedisClientAsync",
|
|
41
|
+
"RedisConnection",
|
|
42
|
+
"RedisConnectionAsync",
|
|
43
|
+
# Helpers
|
|
44
|
+
"RedisConfig",
|
|
45
|
+
]
|
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from contextvars import ContextVar
|
|
4
|
+
from threading import Event
|
|
5
|
+
from typing import Any, NotRequired, TypedDict
|
|
6
|
+
|
|
7
|
+
from redis import (
|
|
8
|
+
Redis as RedisClient,
|
|
9
|
+
ConnectionPool as RedisConnectionPool,
|
|
10
|
+
SSLConnection as RedisSSLConnection,
|
|
11
|
+
Connection as RedisConnection,
|
|
12
|
+
exceptions as RedisExceptions,
|
|
13
|
+
)
|
|
14
|
+
from redis.asyncio import (
|
|
15
|
+
Redis as RedisClientAsync,
|
|
16
|
+
ConnectionPool as RedisConnectionPoolAsync,
|
|
17
|
+
SSLConnection as RedisSSLConnectionAsync,
|
|
18
|
+
Connection as RedisConnectionAsync,
|
|
19
|
+
)
|
|
20
|
+
from redis import exceptions as RedisExceptions
|
|
21
|
+
from redis.retry import Retry as SyncRetry
|
|
22
|
+
from redis.asyncio.retry import Retry as AsyncRetry
|
|
23
|
+
from redis.backoff import ExponentialWithJitterBackoff
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
MODULE_NAME = "py_shared_lib.libs.db.common..kv_conn"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RedisDefaultConfig(TypedDict):
|
|
30
|
+
hostname: str
|
|
31
|
+
"""
|
|
32
|
+
Hostname to connect to.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
port: NotRequired[int]
|
|
36
|
+
"""
|
|
37
|
+
Port to connect to. Default is 6379.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
username: str
|
|
41
|
+
"""
|
|
42
|
+
Username to use for connection. Default is None.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
password: str
|
|
46
|
+
"""
|
|
47
|
+
Password to use for connection. Default is None.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
database: NotRequired[int]
|
|
51
|
+
"""
|
|
52
|
+
Database number to use. Default is 0.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
ssl: NotRequired[bool]
|
|
56
|
+
"""
|
|
57
|
+
Use SSL connection. Default is False.
|
|
58
|
+
|
|
59
|
+
! Note: I don't think this is working at all.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
maxconnections: NotRequired[int]
|
|
63
|
+
"""
|
|
64
|
+
Maximum number of connections in the pool. Default is 20.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
timeout: NotRequired[int]
|
|
68
|
+
"""
|
|
69
|
+
Connection timeout in seconds. Default is 5.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
instant_retries: NotRequired[int]
|
|
73
|
+
"""
|
|
74
|
+
How many retries to do instantly when connection fails.
|
|
75
|
+
Default is 3
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class RedisConfig(TypedDict):
|
|
80
|
+
hostname: str
|
|
81
|
+
port: int
|
|
82
|
+
username: str | None
|
|
83
|
+
password: str | None
|
|
84
|
+
database: int
|
|
85
|
+
ssl: bool
|
|
86
|
+
maxconnections: int
|
|
87
|
+
timeout: int
|
|
88
|
+
instant_retries: int
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class KVDbBase:
|
|
92
|
+
"""
|
|
93
|
+
Key Value Database connection class
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
config: RedisConfig
|
|
97
|
+
timeout: int
|
|
98
|
+
|
|
99
|
+
pool: Any
|
|
100
|
+
context_connection: Any
|
|
101
|
+
|
|
102
|
+
wait_for_connection: bool
|
|
103
|
+
shutdown_requested: Event
|
|
104
|
+
|
|
105
|
+
logger: logging.Logger
|
|
106
|
+
|
|
107
|
+
################################
|
|
108
|
+
### Custom setters / getters ###
|
|
109
|
+
################################
|
|
110
|
+
|
|
111
|
+
_connection: Any
|
|
112
|
+
"""
|
|
113
|
+
Private property to store connection object.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def connection(self) -> Any:
|
|
118
|
+
if not self._connection:
|
|
119
|
+
raise Exception("No connection to redis. Please call open() first.")
|
|
120
|
+
|
|
121
|
+
return self._connection
|
|
122
|
+
|
|
123
|
+
#######################
|
|
124
|
+
### Class lifecycle ###
|
|
125
|
+
#######################
|
|
126
|
+
|
|
127
|
+
def __init__(
|
|
128
|
+
self,
|
|
129
|
+
config: RedisDefaultConfig,
|
|
130
|
+
timeout: int = 5,
|
|
131
|
+
instance_name: str | None = None,
|
|
132
|
+
) -> None:
|
|
133
|
+
self.config = self.fillConfig(config)
|
|
134
|
+
self.timeout = timeout
|
|
135
|
+
|
|
136
|
+
self.pool = None
|
|
137
|
+
self.context_connection = None
|
|
138
|
+
self.wait_for_connection = True
|
|
139
|
+
self.shutdown_requested = Event()
|
|
140
|
+
|
|
141
|
+
self._connection = None
|
|
142
|
+
|
|
143
|
+
instance_name = f" :: {instance_name}" if instance_name else ""
|
|
144
|
+
self.logger_name = f"{__name__}.{self.__class__.__name__}{instance_name}"
|
|
145
|
+
self.logger = logging.getLogger(self.logger_name)
|
|
146
|
+
|
|
147
|
+
def __del__(self) -> None:
|
|
148
|
+
self.logger.debug("Dealloc")
|
|
149
|
+
self.close()
|
|
150
|
+
|
|
151
|
+
########################
|
|
152
|
+
### Context managers ###
|
|
153
|
+
########################
|
|
154
|
+
|
|
155
|
+
def __enter__(self) -> RedisClient:
|
|
156
|
+
self.logger.debug("Creating redis connection")
|
|
157
|
+
|
|
158
|
+
connection = self.new_connection()
|
|
159
|
+
self.context_connection.set(connection)
|
|
160
|
+
return connection
|
|
161
|
+
|
|
162
|
+
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
|
163
|
+
self.logger.debug("Releasing redis connection")
|
|
164
|
+
|
|
165
|
+
redis_conn = self.context_connection.get()
|
|
166
|
+
if redis_conn:
|
|
167
|
+
redis_conn.close()
|
|
168
|
+
|
|
169
|
+
# Reset context
|
|
170
|
+
self.context_connection.set(None)
|
|
171
|
+
|
|
172
|
+
async def __aenter__(self) -> RedisClientAsync:
|
|
173
|
+
self.logger.debug("Creating redis connection")
|
|
174
|
+
|
|
175
|
+
connection = await self.new_connection()
|
|
176
|
+
self.context_connection.set(connection)
|
|
177
|
+
return connection
|
|
178
|
+
|
|
179
|
+
async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
|
180
|
+
self.logger.debug("Releasing redis connection")
|
|
181
|
+
|
|
182
|
+
redis_conn = self.context_connection.get()
|
|
183
|
+
if redis_conn:
|
|
184
|
+
await redis_conn.aclose()
|
|
185
|
+
|
|
186
|
+
# Reset context
|
|
187
|
+
self.context_connection.set(None)
|
|
188
|
+
|
|
189
|
+
###############
|
|
190
|
+
### Helpers ###
|
|
191
|
+
###############
|
|
192
|
+
|
|
193
|
+
def fillConfig(self, config: RedisDefaultConfig) -> RedisConfig:
|
|
194
|
+
return RedisConfig(
|
|
195
|
+
hostname=config["hostname"],
|
|
196
|
+
port=int(config.get("port", 6379)),
|
|
197
|
+
username=config.get("username", None),
|
|
198
|
+
password=config.get("password", None),
|
|
199
|
+
database=int(config.get("database", 0)),
|
|
200
|
+
ssl=bool(config.get("ssl", False)),
|
|
201
|
+
maxconnections=int(config.get("maxconnections", 20)),
|
|
202
|
+
timeout=int(config.get("timeout", 5)),
|
|
203
|
+
instant_retries=int(config.get("instant_retries", 3)),
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
###########################
|
|
207
|
+
### Connection handling ###
|
|
208
|
+
###########################
|
|
209
|
+
|
|
210
|
+
def open(self) -> Any:
|
|
211
|
+
"""
|
|
212
|
+
Open connection to the database and save it in class property.
|
|
213
|
+
"""
|
|
214
|
+
self._connection = self.new_connection()
|
|
215
|
+
|
|
216
|
+
def new_connection(self) -> Any:
|
|
217
|
+
raise NotImplementedError
|
|
218
|
+
|
|
219
|
+
def close(self) -> Any:
|
|
220
|
+
"""
|
|
221
|
+
Basic class without pool does not need to close anything,
|
|
222
|
+
thus this method is empty by default.
|
|
223
|
+
"""
|
|
224
|
+
...
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class RedisDB(KVDbBase):
|
|
228
|
+
context_connection: ContextVar[RedisClient | None]
|
|
229
|
+
|
|
230
|
+
_connection: RedisClient
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def connection(self) -> RedisClient:
|
|
234
|
+
return super().connection
|
|
235
|
+
|
|
236
|
+
def __init__(
|
|
237
|
+
self,
|
|
238
|
+
config: RedisDefaultConfig,
|
|
239
|
+
timeout: int = 5,
|
|
240
|
+
instance_name: str | None = None,
|
|
241
|
+
) -> None:
|
|
242
|
+
super().__init__(config=config, timeout=timeout, instance_name=instance_name)
|
|
243
|
+
|
|
244
|
+
self.context_connection = ContextVar("RedisDB", default=None)
|
|
245
|
+
|
|
246
|
+
def new_connection(self) -> RedisClient:
|
|
247
|
+
tries = 0
|
|
248
|
+
while self.wait_for_connection and not self.shutdown_requested.is_set():
|
|
249
|
+
logBuffer = f"Attempt #{tries + 1} to connect to redis .. "
|
|
250
|
+
redis_conn = None
|
|
251
|
+
try:
|
|
252
|
+
redis_conn = RedisClient(
|
|
253
|
+
host=self.config["hostname"],
|
|
254
|
+
port=self.config["port"],
|
|
255
|
+
username=self.config["username"],
|
|
256
|
+
password=self.config["password"],
|
|
257
|
+
db=self.config["database"],
|
|
258
|
+
socket_connect_timeout=self.timeout,
|
|
259
|
+
socket_keepalive=True,
|
|
260
|
+
retry_on_timeout=False,
|
|
261
|
+
retry=SyncRetry(
|
|
262
|
+
backoff=ExponentialWithJitterBackoff(base=1, cap=10),
|
|
263
|
+
retries=0,
|
|
264
|
+
),
|
|
265
|
+
protocol=3,
|
|
266
|
+
decode_responses=True,
|
|
267
|
+
)
|
|
268
|
+
redis_conn.ping() # type: ignore
|
|
269
|
+
self.logger.debug(f"{logBuffer}OK")
|
|
270
|
+
return redis_conn
|
|
271
|
+
|
|
272
|
+
except RedisExceptions.RedisError as e:
|
|
273
|
+
if redis_conn:
|
|
274
|
+
redis_conn.close() # type: ignore
|
|
275
|
+
|
|
276
|
+
self.logger.error(f"{logBuffer}ERR ({e})")
|
|
277
|
+
self.shutdown_requested.wait(self.timeout)
|
|
278
|
+
tries += 1
|
|
279
|
+
if tries > 3:
|
|
280
|
+
raise
|
|
281
|
+
continue
|
|
282
|
+
|
|
283
|
+
raise Exception("Cancelled connection creation")
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class RedisDBAsync(KVDbBase):
|
|
287
|
+
context_connection: ContextVar[RedisClientAsync | None]
|
|
288
|
+
|
|
289
|
+
_connection: RedisClientAsync | None
|
|
290
|
+
|
|
291
|
+
@property
|
|
292
|
+
def connection(self) -> RedisClientAsync:
|
|
293
|
+
return super().connection
|
|
294
|
+
|
|
295
|
+
def __init__(
|
|
296
|
+
self,
|
|
297
|
+
config: RedisDefaultConfig,
|
|
298
|
+
timeout: int = 5,
|
|
299
|
+
instance_name: str | None = None,
|
|
300
|
+
) -> None:
|
|
301
|
+
super().__init__(config=config, timeout=timeout, instance_name=instance_name)
|
|
302
|
+
|
|
303
|
+
self.context_connection = ContextVar("RedisDBAsync", default=None)
|
|
304
|
+
|
|
305
|
+
async def new_connection(self) -> RedisClientAsync:
|
|
306
|
+
tries = 0
|
|
307
|
+
while self.wait_for_connection and not self.shutdown_requested.is_set():
|
|
308
|
+
self.logger.debug(f"Attempting to connect to redis .. ", extra={"end": ""})
|
|
309
|
+
redis_conn = None
|
|
310
|
+
try:
|
|
311
|
+
redis_conn = RedisClientAsync(
|
|
312
|
+
host=self.config["hostname"],
|
|
313
|
+
port=self.config["port"],
|
|
314
|
+
username=self.config["username"],
|
|
315
|
+
password=self.config["password"],
|
|
316
|
+
db=self.config["database"],
|
|
317
|
+
socket_connect_timeout=self.timeout,
|
|
318
|
+
socket_keepalive=True,
|
|
319
|
+
retry_on_timeout=False,
|
|
320
|
+
retry=AsyncRetry(
|
|
321
|
+
backoff=ExponentialWithJitterBackoff(base=1, cap=10),
|
|
322
|
+
retries=0,
|
|
323
|
+
),
|
|
324
|
+
protocol=3,
|
|
325
|
+
decode_responses=True,
|
|
326
|
+
)
|
|
327
|
+
await redis_conn.ping() # type: ignore
|
|
328
|
+
self.logger.debug("OK", extra={"clean": True})
|
|
329
|
+
return redis_conn
|
|
330
|
+
|
|
331
|
+
except RedisExceptions.RedisError as e:
|
|
332
|
+
if redis_conn:
|
|
333
|
+
await redis_conn.close()
|
|
334
|
+
|
|
335
|
+
self.logger.error(f"ERR ({e})", extra={"clean": True})
|
|
336
|
+
self.shutdown_requested.wait(self.timeout)
|
|
337
|
+
tries += 1
|
|
338
|
+
if tries > 3:
|
|
339
|
+
raise
|
|
340
|
+
continue
|
|
341
|
+
|
|
342
|
+
raise Exception("Cancelled connection creation")
|
|
343
|
+
|
|
344
|
+
async def open(self) -> None:
|
|
345
|
+
"""
|
|
346
|
+
Open connection to the database and save it in class property.
|
|
347
|
+
"""
|
|
348
|
+
self._connection = await self.new_connection()
|
|
349
|
+
|
|
350
|
+
async def close(self) -> None:
|
|
351
|
+
"""
|
|
352
|
+
Close connection to the database.
|
|
353
|
+
"""
|
|
354
|
+
if self._connection:
|
|
355
|
+
await self._connection.aclose()
|
|
356
|
+
self._connection = None
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
class RedisDBWithPool(KVDbBase):
|
|
360
|
+
pool: RedisConnectionPool
|
|
361
|
+
context_connection: ContextVar[RedisClient | None]
|
|
362
|
+
|
|
363
|
+
_connection: RedisClient | None
|
|
364
|
+
|
|
365
|
+
@property
|
|
366
|
+
def connection(self) -> RedisClient:
|
|
367
|
+
return super().connection
|
|
368
|
+
|
|
369
|
+
def __init__(
|
|
370
|
+
self,
|
|
371
|
+
config: RedisDefaultConfig,
|
|
372
|
+
timeout: int = 5,
|
|
373
|
+
instance_name: str | None = None,
|
|
374
|
+
) -> None:
|
|
375
|
+
super().__init__(config=config, timeout=timeout, instance_name=instance_name)
|
|
376
|
+
|
|
377
|
+
self.pool = RedisConnectionPool(
|
|
378
|
+
connection_class=(
|
|
379
|
+
RedisSSLConnection if self.config["ssl"] else RedisConnection
|
|
380
|
+
),
|
|
381
|
+
max_connections=self.config["maxconnections"],
|
|
382
|
+
host=self.config["hostname"],
|
|
383
|
+
port=self.config["port"],
|
|
384
|
+
username=self.config["username"],
|
|
385
|
+
password=self.config["password"],
|
|
386
|
+
db=self.config["database"],
|
|
387
|
+
socket_connect_timeout=self.timeout,
|
|
388
|
+
socket_keepalive=True,
|
|
389
|
+
retry_on_timeout=False,
|
|
390
|
+
retry=False,
|
|
391
|
+
protocol=3,
|
|
392
|
+
decode_responses=True,
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
self.context_connection = ContextVar("RedisDBWithPool", default=None)
|
|
396
|
+
|
|
397
|
+
def new_connection(self) -> RedisClient:
|
|
398
|
+
tries = 0
|
|
399
|
+
while self.wait_for_connection and not self.shutdown_requested.is_set():
|
|
400
|
+
logBuffer = f"Attempt #{tries + 1} to connect to redis .. "
|
|
401
|
+
redis_conn = None
|
|
402
|
+
try:
|
|
403
|
+
redis_conn = RedisClient(connection_pool=self.pool)
|
|
404
|
+
redis_conn.ping() # type: ignore
|
|
405
|
+
self.logger.debug(f"{logBuffer}OK")
|
|
406
|
+
return redis_conn
|
|
407
|
+
|
|
408
|
+
except RedisExceptions.RedisError as e:
|
|
409
|
+
if redis_conn:
|
|
410
|
+
redis_conn.close() # type: ignore
|
|
411
|
+
|
|
412
|
+
self.logger.error(f"{logBuffer}ERR ({e})")
|
|
413
|
+
self.shutdown_requested.wait(self.timeout)
|
|
414
|
+
tries += 1
|
|
415
|
+
if tries > 3:
|
|
416
|
+
raise
|
|
417
|
+
continue
|
|
418
|
+
|
|
419
|
+
raise Exception("Cancelled connection creation")
|
|
420
|
+
|
|
421
|
+
def close(self) -> None:
|
|
422
|
+
if self.shutdown_requested.is_set():
|
|
423
|
+
return
|
|
424
|
+
|
|
425
|
+
self.logger.debug("Closing redis connection pool")
|
|
426
|
+
self.shutdown_requested.set()
|
|
427
|
+
|
|
428
|
+
# Close pool
|
|
429
|
+
self.pool.disconnect()
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
class RedisDBWithPoolAsync(KVDbBase):
|
|
433
|
+
pool: RedisConnectionPoolAsync
|
|
434
|
+
context_connection: ContextVar[RedisClientAsync | None]
|
|
435
|
+
|
|
436
|
+
_connection: RedisClientAsync | None
|
|
437
|
+
|
|
438
|
+
@property
|
|
439
|
+
def connection(self) -> RedisClientAsync:
|
|
440
|
+
return super().connection
|
|
441
|
+
|
|
442
|
+
def __init__(
|
|
443
|
+
self,
|
|
444
|
+
config: RedisDefaultConfig,
|
|
445
|
+
timeout: int = 5,
|
|
446
|
+
instance_name: str | None = None,
|
|
447
|
+
) -> None:
|
|
448
|
+
super().__init__(config=config, timeout=timeout, instance_name=instance_name)
|
|
449
|
+
|
|
450
|
+
self.pool = RedisConnectionPoolAsync(
|
|
451
|
+
connection_class=(
|
|
452
|
+
RedisSSLConnectionAsync if self.config["ssl"] else RedisConnectionAsync
|
|
453
|
+
),
|
|
454
|
+
max_connections=self.config["maxconnections"],
|
|
455
|
+
host=self.config["hostname"],
|
|
456
|
+
port=self.config["port"],
|
|
457
|
+
username=self.config["username"],
|
|
458
|
+
password=self.config["password"],
|
|
459
|
+
db=self.config["database"],
|
|
460
|
+
socket_connect_timeout=timeout,
|
|
461
|
+
socket_keepalive=True,
|
|
462
|
+
retry_on_timeout=False,
|
|
463
|
+
retry=False,
|
|
464
|
+
protocol=3,
|
|
465
|
+
decode_responses=True,
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
self.context_connection = ContextVar("RedisDBWithPoolAsync", default=None)
|
|
469
|
+
|
|
470
|
+
async def new_connection(self) -> RedisClientAsync:
|
|
471
|
+
tries = 0
|
|
472
|
+
while self.wait_for_connection and not self.shutdown_requested.is_set():
|
|
473
|
+
self.logger.debug(f"Attempting to connect to redis .. ", extra={"end": ""})
|
|
474
|
+
redis_conn = None
|
|
475
|
+
try:
|
|
476
|
+
redis_conn = RedisClientAsync(connection_pool=self.pool)
|
|
477
|
+
await redis_conn.ping() # type: ignore
|
|
478
|
+
self.logger.debug("OK", extra={"clean": True})
|
|
479
|
+
return redis_conn
|
|
480
|
+
|
|
481
|
+
except RedisExceptions.RedisError as e:
|
|
482
|
+
if redis_conn:
|
|
483
|
+
await redis_conn.close()
|
|
484
|
+
|
|
485
|
+
self.logger.error(f"ERR ({e})", extra={"clean": True})
|
|
486
|
+
self.shutdown_requested.wait(self.timeout)
|
|
487
|
+
tries += 1
|
|
488
|
+
if tries > 3:
|
|
489
|
+
raise
|
|
490
|
+
continue
|
|
491
|
+
|
|
492
|
+
raise Exception("Cancelled connection creation")
|
|
493
|
+
|
|
494
|
+
async def close(self) -> None:
|
|
495
|
+
if self.shutdown_requested.is_set():
|
|
496
|
+
return
|
|
497
|
+
|
|
498
|
+
self.logger.debug("Closing redis connection pool")
|
|
499
|
+
self.shutdown_requested.set()
|
|
500
|
+
|
|
501
|
+
# Close pool
|
|
502
|
+
await self.pool.disconnect()
|
|
File without changes
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: database_wrapper_redis
|
|
3
|
+
Version: 0.2.5
|
|
4
|
+
Summary: database_wrapper for Redis database
|
|
5
|
+
Author-email: Gints Murans <gm@gm.lv>
|
|
6
|
+
License: GNU General Public License v3.0 (GPL-3.0)
|
|
7
|
+
Project-URL: Homepage, https://github.com/gintsmurans/py_database_wrapper
|
|
8
|
+
Project-URL: Documentation, https://github.com/gintsmurans/py_database_wrapper
|
|
9
|
+
Project-URL: Changes, https://github.com/gintsmurans/py_database_wrapper
|
|
10
|
+
Project-URL: Code, https://github.com/gintsmurans/py_database_wrapper
|
|
11
|
+
Project-URL: Issue Tracker, https://github.com/gintsmurans/py_database_wrapper/issues
|
|
12
|
+
Project-URL: Download, https://pypi.org/project/database_wrapper/
|
|
13
|
+
Keywords: database,wrapper,python,redis
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
|
17
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
18
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
19
|
+
Classifier: Operating System :: POSIX
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
27
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
28
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
29
|
+
Classifier: Topic :: Database
|
|
30
|
+
Classifier: Topic :: Database :: Front-Ends
|
|
31
|
+
Classifier: Topic :: Software Development
|
|
32
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
33
|
+
Requires-Python: >=3.8
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
Requires-Dist: database_wrapper==0.2.5
|
|
36
|
+
Requires-Dist: redis
|
|
37
|
+
|
|
38
|
+
# database_wrapper_redis
|
|
39
|
+
|
|
40
|
+
_Part of the `database_wrapper` package._
|
|
41
|
+
|
|
42
|
+
This python package is a database wrapper for [Redis](https://redis.io/).
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install database_wrapper[redis]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from database_wrapper_redis import RedisDBWithPoolAsync, RedisDB
|
|
54
|
+
|
|
55
|
+
db = RedisDBWithPoolAsync({
|
|
56
|
+
"hostname": "localhost",
|
|
57
|
+
"port": 3306,
|
|
58
|
+
"username": "root",
|
|
59
|
+
"password": "your_password",
|
|
60
|
+
"database": 0
|
|
61
|
+
})
|
|
62
|
+
await db.open()
|
|
63
|
+
try:
|
|
64
|
+
async with db as redis_con:
|
|
65
|
+
await redis_con.set("key", "value")
|
|
66
|
+
value = await redis_con.get("key")
|
|
67
|
+
print(value) # Output: b'value'
|
|
68
|
+
|
|
69
|
+
finally:
|
|
70
|
+
await db.close()
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Notes
|
|
74
|
+
No wrapper at this time, as redis is just a key-value store.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
database_wrapper_redis/__init__.py
|
|
4
|
+
database_wrapper_redis/connector.py
|
|
5
|
+
database_wrapper_redis/py.typed
|
|
6
|
+
database_wrapper_redis.egg-info/PKG-INFO
|
|
7
|
+
database_wrapper_redis.egg-info/SOURCES.txt
|
|
8
|
+
database_wrapper_redis.egg-info/dependency_links.txt
|
|
9
|
+
database_wrapper_redis.egg-info/requires.txt
|
|
10
|
+
database_wrapper_redis.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
database_wrapper_redis
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools >= 61.0.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "database_wrapper_redis"
|
|
7
|
+
version = "0.2.5"
|
|
8
|
+
description = "database_wrapper for Redis database"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = {text = "GNU General Public License v3.0 (GPL-3.0)"}
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "Gints Murans", email = "gm@gm.lv"}
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
|
|
19
|
+
"Operating System :: MacOS :: MacOS X",
|
|
20
|
+
"Operating System :: Microsoft :: Windows",
|
|
21
|
+
"Operating System :: POSIX",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3.8",
|
|
24
|
+
"Programming Language :: Python :: 3.9",
|
|
25
|
+
"Programming Language :: Python :: 3.10",
|
|
26
|
+
"Programming Language :: Python :: 3.11",
|
|
27
|
+
"Programming Language :: Python :: 3.12",
|
|
28
|
+
"Programming Language :: Python :: 3.13",
|
|
29
|
+
"Programming Language :: Python :: Implementation :: CPython",
|
|
30
|
+
"Programming Language :: Python :: Implementation :: PyPy",
|
|
31
|
+
"Topic :: Database",
|
|
32
|
+
"Topic :: Database :: Front-Ends",
|
|
33
|
+
"Topic :: Software Development",
|
|
34
|
+
"Topic :: Software Development :: Libraries :: Python Modules"
|
|
35
|
+
]
|
|
36
|
+
keywords = ["database", "wrapper", "python", "redis"]
|
|
37
|
+
dependencies = [
|
|
38
|
+
"database_wrapper == 0.2.5",
|
|
39
|
+
"redis",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[project.urls]
|
|
43
|
+
Homepage = "https://github.com/gintsmurans/py_database_wrapper"
|
|
44
|
+
Documentation = "https://github.com/gintsmurans/py_database_wrapper"
|
|
45
|
+
Changes = "https://github.com/gintsmurans/py_database_wrapper"
|
|
46
|
+
Code = "https://github.com/gintsmurans/py_database_wrapper"
|
|
47
|
+
"Issue Tracker" = "https://github.com/gintsmurans/py_database_wrapper/issues"
|
|
48
|
+
Download = "https://pypi.org/project/database_wrapper/"
|
|
49
|
+
|
|
50
|
+
[tool.setuptools.package-data]
|
|
51
|
+
database_wrapper_redis = ["py.typed"]
|