wredis 0.1.0__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.
- wredis-0.1.0/LICENSE +21 -0
- wredis-0.1.0/PKG-INFO +61 -0
- wredis-0.1.0/README.md +20 -0
- wredis-0.1.0/pyproject.toml +23 -0
- wredis-0.1.0/setup.cfg +4 -0
- wredis-0.1.0/setup.py +32 -0
- wredis-0.1.0/wredis/__init__.py +0 -0
- wredis-0.1.0/wredis/bitmap/__init__.py +1 -0
- wredis-0.1.0/wredis/bitmap/bitmap.py +143 -0
- wredis-0.1.0/wredis/hash/__init__.py +1 -0
- wredis-0.1.0/wredis/hash/hash.py +216 -0
- wredis-0.1.0/wredis/pubsub/__init__.py +1 -0
- wredis-0.1.0/wredis/pubsub/pupsub.py +175 -0
- wredis-0.1.0/wredis/queue/__init__.py +1 -0
- wredis-0.1.0/wredis/queue/queue.py +205 -0
- wredis-0.1.0/wredis/sets/__init__.py +1 -0
- wredis-0.1.0/wredis/sets/sets.py +158 -0
- wredis-0.1.0/wredis/sortedset/__init__.py +1 -0
- wredis-0.1.0/wredis/sortedset/sortedset.py +287 -0
- wredis-0.1.0/wredis/streams/__init__.py +1 -0
- wredis-0.1.0/wredis/streams/streams.py +220 -0
- wredis-0.1.0/wredis.egg-info/PKG-INFO +61 -0
- wredis-0.1.0/wredis.egg-info/SOURCES.txt +23 -0
- wredis-0.1.0/wredis.egg-info/dependency_links.txt +1 -0
- wredis-0.1.0/wredis.egg-info/top_level.txt +1 -0
wredis-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 William Rodriguez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
wredis-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: wredis
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Redis control with Python
|
|
5
|
+
Home-page: https://github.com/wisrovi/wredis
|
|
6
|
+
Author: William Steve Rodriguez Villamizar
|
|
7
|
+
Author-email: wisrovi <wisrovi.rodriguez@gmail.com>
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2025 William Rodriguez
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
+
in the Software without restriction, including without limitation the rights
|
|
15
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
+
furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
copies or substantial portions of the Software.
|
|
21
|
+
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
+
SOFTWARE.
|
|
29
|
+
|
|
30
|
+
Project-URL: Homepage, https://github.com/wisrovi/wredis
|
|
31
|
+
Project-URL: Bug Tracker, https://github.com/wisrovi/wredis/issues
|
|
32
|
+
Classifier: Programming Language :: Python :: 3
|
|
33
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
34
|
+
Classifier: Operating System :: OS Independent
|
|
35
|
+
Requires-Python: >=3.6, <3.12
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
License-File: LICENSE
|
|
38
|
+
Dynamic: author
|
|
39
|
+
Dynamic: home-page
|
|
40
|
+
Dynamic: requires-python
|
|
41
|
+
|
|
42
|
+
# wredis
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
my_project/
|
|
46
|
+
├── .github/
|
|
47
|
+
│ └── workflows/
|
|
48
|
+
│ └── release-to-pypi.yml # Archivo de configuración para GitHub Actions
|
|
49
|
+
├── my_project/ # Carpeta con el código fuente
|
|
50
|
+
│ ├── __init__.py # Marca la carpeta como módulo de Python
|
|
51
|
+
│ └── main.py # Archivo principal (puede tener otros módulos)
|
|
52
|
+
├── tests/ # Carpeta con pruebas del proyecto
|
|
53
|
+
│ ├── __init__.py
|
|
54
|
+
│ └── test_main.py # Archivo de pruebas (puedes agregar más)
|
|
55
|
+
├── LICENSE # Licencia del proyecto (ej. MIT, Apache)
|
|
56
|
+
├── README.md # Descripción del proyecto
|
|
57
|
+
├── setup.py # Configuración de empaquetado para PyPI
|
|
58
|
+
├── pyproject.toml # Configuración moderna para herramientas de empaquetado
|
|
59
|
+
├── requirements.txt # Dependencias del proyecto
|
|
60
|
+
├── .gitignore # Archivos y carpetas ignorados por Git
|
|
61
|
+
└── dist/ # Carpeta donde se generarán los paquetes (se crea al construir el paquete)
|
wredis-0.1.0/README.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# wredis
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
my_project/
|
|
5
|
+
├── .github/
|
|
6
|
+
│ └── workflows/
|
|
7
|
+
│ └── release-to-pypi.yml # Archivo de configuración para GitHub Actions
|
|
8
|
+
├── my_project/ # Carpeta con el código fuente
|
|
9
|
+
│ ├── __init__.py # Marca la carpeta como módulo de Python
|
|
10
|
+
│ └── main.py # Archivo principal (puede tener otros módulos)
|
|
11
|
+
├── tests/ # Carpeta con pruebas del proyecto
|
|
12
|
+
│ ├── __init__.py
|
|
13
|
+
│ └── test_main.py # Archivo de pruebas (puedes agregar más)
|
|
14
|
+
├── LICENSE # Licencia del proyecto (ej. MIT, Apache)
|
|
15
|
+
├── README.md # Descripción del proyecto
|
|
16
|
+
├── setup.py # Configuración de empaquetado para PyPI
|
|
17
|
+
├── pyproject.toml # Configuración moderna para herramientas de empaquetado
|
|
18
|
+
├── requirements.txt # Dependencias del proyecto
|
|
19
|
+
├── .gitignore # Archivos y carpetas ignorados por Git
|
|
20
|
+
└── dist/ # Carpeta donde se generarán los paquetes (se crea al construir el paquete)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "wredis"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="wisrovi", email="wisrovi.rodriguez@gmail.com" },
|
|
10
|
+
]
|
|
11
|
+
description = "Redis control with Python"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
license = { file="LICENSE" }
|
|
14
|
+
requires-python = ">=3.8"
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
"Homepage" = "https://github.com/wisrovi/wredis"
|
|
23
|
+
"Bug Tracker" = "https://github.com/wisrovi/wredis/issues"
|
wredis-0.1.0/setup.cfg
ADDED
wredis-0.1.0/setup.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from setuptools import setup, find_packages
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
this_directory = Path(__file__).parent
|
|
7
|
+
long_description = (this_directory / "README.md").read_text()
|
|
8
|
+
|
|
9
|
+
setup(
|
|
10
|
+
name="wredis", # Nombre del paquete en PyPI
|
|
11
|
+
version="0.1.0", # Versión inicial
|
|
12
|
+
packages=find_packages(),
|
|
13
|
+
install_requires=[
|
|
14
|
+
"redis",
|
|
15
|
+
"loguru",
|
|
16
|
+
],
|
|
17
|
+
classifiers=[
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Topic :: Software Development :: Build Tools",
|
|
22
|
+
"Intended Audience :: Developers",
|
|
23
|
+
],
|
|
24
|
+
description="Redis easy control",
|
|
25
|
+
long_description_content_type="text/markdown",
|
|
26
|
+
long_description=long_description,
|
|
27
|
+
url="https://github.com/wisrovi/wredis",
|
|
28
|
+
author="William Steve Rodriguez Villamizar",
|
|
29
|
+
author_email="wisrovi.rodriguez@gmail.com",
|
|
30
|
+
license="MIT",
|
|
31
|
+
python_requires=">=3.6, <3.12", # Requiere Python >=3.6 y <3.10
|
|
32
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .bitmap import RedisBitmapManager
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import redis
|
|
2
|
+
from loguru import logger
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class RedisBitmapManager:
|
|
6
|
+
"""
|
|
7
|
+
Manages Redis bitmap operations, including setting, retrieving, and counting bits,
|
|
8
|
+
as well as managing TTL (Time-to-Live) for bitmap keys.
|
|
9
|
+
|
|
10
|
+
Attributes:
|
|
11
|
+
redis_client (redis.StrictRedis): Redis client instance.
|
|
12
|
+
verbose (bool): Enables detailed logging if True.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
host: str = "localhost",
|
|
18
|
+
port: int = 6379,
|
|
19
|
+
db: int = 0,
|
|
20
|
+
verbose: bool = True,
|
|
21
|
+
):
|
|
22
|
+
"""
|
|
23
|
+
Initializes the RedisBitmapManager with connection details.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
host (str): Hostname of the Redis server.
|
|
27
|
+
port (int): Port number of the Redis server.
|
|
28
|
+
db (int): Redis database index.
|
|
29
|
+
verbose (bool): Enable detailed logging if True.
|
|
30
|
+
"""
|
|
31
|
+
self.redis_client = redis.StrictRedis(host=host, port=port, db=db)
|
|
32
|
+
self.verbose = verbose
|
|
33
|
+
|
|
34
|
+
def log(self, message: str, level: str = "info") -> None:
|
|
35
|
+
"""
|
|
36
|
+
Logs a message if verbose mode is enabled.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
message (str): The message to log.
|
|
40
|
+
level (str): The log level (e.g., "info", "warning", "error").
|
|
41
|
+
"""
|
|
42
|
+
if self.verbose:
|
|
43
|
+
getattr(logger, level)(message)
|
|
44
|
+
|
|
45
|
+
def set_bit(self, key: str, offset: int, value: int, ttl: int = -1) -> None:
|
|
46
|
+
"""
|
|
47
|
+
Sets a bit at a specific position in a bitmap and optionally sets a TTL.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
key (str): The Redis key for the bitmap.
|
|
51
|
+
offset (int): The position of the bit to set.
|
|
52
|
+
value (int): The value to set the bit to (0 or 1).
|
|
53
|
+
ttl (int): The time-to-live for the key in seconds. If -1, no TTL is set.
|
|
54
|
+
"""
|
|
55
|
+
try:
|
|
56
|
+
self.redis_client.setbit(key, offset, value)
|
|
57
|
+
self.log(f"Set bit in '{key}' at position {offset} to value {value}.")
|
|
58
|
+
|
|
59
|
+
if ttl > 0:
|
|
60
|
+
self.redis_client.expire(key, ttl)
|
|
61
|
+
self.log(f"Set TTL of {ttl} seconds for '{key}'.")
|
|
62
|
+
except Exception as e:
|
|
63
|
+
logger.error(f"Error setting bit in '{key}': {e}")
|
|
64
|
+
|
|
65
|
+
def get_bit(self, key: str, offset: int) -> int:
|
|
66
|
+
"""
|
|
67
|
+
Retrieves the value of a bit at a specific position in a bitmap.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
key (str): The Redis key for the bitmap.
|
|
71
|
+
offset (int): The position of the bit to retrieve.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
int: The value of the bit (0 or 1).
|
|
75
|
+
"""
|
|
76
|
+
try:
|
|
77
|
+
bit_value = self.redis_client.getbit(key, offset)
|
|
78
|
+
self.log(f"Bit value in '{key}' at position {offset}: {bit_value}.")
|
|
79
|
+
return bit_value
|
|
80
|
+
except Exception as e:
|
|
81
|
+
logger.error(f"Error retrieving bit from '{key}': {e}")
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
def count_bits(self, key: str) -> int:
|
|
85
|
+
"""
|
|
86
|
+
Counts the number of bits set to 1 in a bitmap.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
key (str): The Redis key for the bitmap.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
int: The number of bits set to 1.
|
|
93
|
+
"""
|
|
94
|
+
try:
|
|
95
|
+
bit_count = self.redis_client.bitcount(key)
|
|
96
|
+
self.log(f"Number of bits set to 1 in '{key}': {bit_count}.")
|
|
97
|
+
return bit_count
|
|
98
|
+
except Exception as e:
|
|
99
|
+
logger.error(f"Error counting bits in '{key}': {e}")
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
def get_ttl(self, key: str) -> int:
|
|
103
|
+
"""
|
|
104
|
+
Retrieves the time-to-live (TTL) for a bitmap key.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
key (str): The Redis key for the bitmap.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
int: The TTL in seconds. -1 if no TTL is set, -2 if the key does not exist.
|
|
111
|
+
"""
|
|
112
|
+
try:
|
|
113
|
+
ttl = self.redis_client.ttl(key)
|
|
114
|
+
if ttl == -1:
|
|
115
|
+
self.log(f"The bitmap '{key}' has no TTL set.", level="warning")
|
|
116
|
+
elif ttl == -2:
|
|
117
|
+
self.log(f"The bitmap '{key}' does not exist.", level="warning")
|
|
118
|
+
else:
|
|
119
|
+
self.log(f"The TTL for bitmap '{key}' is {ttl} seconds.")
|
|
120
|
+
return ttl
|
|
121
|
+
except Exception as e:
|
|
122
|
+
logger.error(f"Error retrieving TTL for '{key}': {e}")
|
|
123
|
+
return -2
|
|
124
|
+
|
|
125
|
+
def extend_ttl(self, key: str, ttl: int) -> None:
|
|
126
|
+
"""
|
|
127
|
+
Extends or sets a new TTL for a bitmap key.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
key (str): The Redis key for the bitmap.
|
|
131
|
+
ttl (int): The new TTL in seconds.
|
|
132
|
+
"""
|
|
133
|
+
try:
|
|
134
|
+
if self.redis_client.exists(key):
|
|
135
|
+
self.redis_client.expire(key, ttl)
|
|
136
|
+
self.log(f"Extended TTL for bitmap '{key}' to {ttl} seconds.")
|
|
137
|
+
else:
|
|
138
|
+
self.log(
|
|
139
|
+
f"Cannot set TTL because the bitmap '{key}' does not exist.",
|
|
140
|
+
level="warning",
|
|
141
|
+
)
|
|
142
|
+
except Exception as e:
|
|
143
|
+
logger.error(f"Error extending TTL for '{key}': {e}")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .hash import RedisHashManager
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import redis
|
|
3
|
+
from loguru import logger
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class RedisHashManager:
|
|
7
|
+
"""
|
|
8
|
+
Manages Redis hash operations, including creation, reading, updating,
|
|
9
|
+
deleting fields, and managing TTL (Time-to-Live).
|
|
10
|
+
|
|
11
|
+
Attributes:
|
|
12
|
+
redis_client (redis.StrictRedis): Redis client instance.
|
|
13
|
+
verbose (bool): Enables detailed logging if True.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
host: str = "localhost",
|
|
19
|
+
port: int = 6379,
|
|
20
|
+
db: int = 0,
|
|
21
|
+
verbose: bool = True,
|
|
22
|
+
):
|
|
23
|
+
"""
|
|
24
|
+
Initializes the RedisHashManager with connection details.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
host (str): Hostname of the Redis server.
|
|
28
|
+
port (int): Port number of the Redis server.
|
|
29
|
+
db (int): Redis database index.
|
|
30
|
+
verbose (bool): Enable detailed logging if True.
|
|
31
|
+
"""
|
|
32
|
+
self.redis_client = redis.StrictRedis(host=host, port=port, db=db)
|
|
33
|
+
self.verbose = verbose
|
|
34
|
+
|
|
35
|
+
def log(self, message: str, level: str = "info") -> None:
|
|
36
|
+
"""
|
|
37
|
+
Logs a message if verbose mode is enabled.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
message (str): The message to log.
|
|
41
|
+
level (str): The log level (e.g., "info", "warning", "error").
|
|
42
|
+
"""
|
|
43
|
+
if self.verbose:
|
|
44
|
+
getattr(logger, level)(message)
|
|
45
|
+
|
|
46
|
+
def create_hash(
|
|
47
|
+
self, hash_name: str, key: str, value: dict | str, ttl: int = -1
|
|
48
|
+
) -> None:
|
|
49
|
+
"""
|
|
50
|
+
Writes a key-value pair into a Redis hash and optionally sets a TTL.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
hash_name (str): Name of the hash in Redis.
|
|
54
|
+
key (str): Key within the hash.
|
|
55
|
+
value (dict | str): Value to store, serialized to JSON if it is a dictionary.
|
|
56
|
+
ttl (int): Time-to-live for the hash in seconds. If -1, no TTL is set.
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
json_value = json.dumps(value) if isinstance(value, dict) else value
|
|
60
|
+
self.redis_client.hset(hash_name, key, json_value)
|
|
61
|
+
self.log(f"Written to hash '{hash_name}' -> {key}: {value}")
|
|
62
|
+
|
|
63
|
+
if ttl > 0:
|
|
64
|
+
self.redis_client.expire(hash_name, ttl)
|
|
65
|
+
self.log(f"Set TTL of {ttl} seconds for hash '{hash_name}'")
|
|
66
|
+
except Exception as e:
|
|
67
|
+
logger.error(f"Error writing to hash '{hash_name}': {e}")
|
|
68
|
+
|
|
69
|
+
def read_hash(self, hash_name: str, key: str) -> dict | str | None:
|
|
70
|
+
"""
|
|
71
|
+
Reads a key-value pair from a Redis hash.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
hash_name (str): Name of the hash in Redis.
|
|
75
|
+
key (str): Key within the hash.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
dict | str | None: The value stored, deserialized from JSON if applicable, or None if not found.
|
|
79
|
+
"""
|
|
80
|
+
try:
|
|
81
|
+
json_value = self.redis_client.hget(hash_name, key)
|
|
82
|
+
if json_value:
|
|
83
|
+
json_value = json_value.decode()
|
|
84
|
+
try:
|
|
85
|
+
return json.loads(json_value)
|
|
86
|
+
except json.JSONDecodeError:
|
|
87
|
+
return json_value
|
|
88
|
+
else:
|
|
89
|
+
self.log(
|
|
90
|
+
f"Field '{key}' does not exist in hash '{hash_name}'.",
|
|
91
|
+
level="warning",
|
|
92
|
+
)
|
|
93
|
+
return None
|
|
94
|
+
except Exception as e:
|
|
95
|
+
logger.error(f"Error reading from hash '{hash_name}': {e}")
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
def update_hash(self, hash_name: str, key: str, new_data: dict) -> None:
|
|
99
|
+
"""
|
|
100
|
+
Updates a key-value pair in a Redis hash. If the field does not exist, it adds it.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
hash_name (str): Name of the hash in Redis.
|
|
104
|
+
key (str): Key within the hash.
|
|
105
|
+
new_data (dict): New data to update the field.
|
|
106
|
+
"""
|
|
107
|
+
try:
|
|
108
|
+
current_value = self.read_hash(hash_name, key)
|
|
109
|
+
|
|
110
|
+
if isinstance(current_value, dict):
|
|
111
|
+
current_value.update(new_data)
|
|
112
|
+
self.create_hash(hash_name, key, current_value)
|
|
113
|
+
self.log(
|
|
114
|
+
f"Updated field '{key}' in hash '{hash_name}': {current_value}"
|
|
115
|
+
)
|
|
116
|
+
else:
|
|
117
|
+
self.create_hash(hash_name, key, new_data)
|
|
118
|
+
self.log(f"Added new field '{key}' to hash '{hash_name}': {new_data}")
|
|
119
|
+
except Exception as e:
|
|
120
|
+
logger.error(f"Error updating field '{key}' in hash '{hash_name}': {e}")
|
|
121
|
+
|
|
122
|
+
def delete_hash_field(self, hash_name: str, key: str) -> None:
|
|
123
|
+
"""
|
|
124
|
+
Deletes a specific field from a Redis hash.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
hash_name (str): Name of the hash in Redis.
|
|
128
|
+
key (str): Key within the hash to delete.
|
|
129
|
+
"""
|
|
130
|
+
try:
|
|
131
|
+
result = self.redis_client.hdel(hash_name, key)
|
|
132
|
+
if result:
|
|
133
|
+
self.log(f"Deleted field '{key}' from hash '{hash_name}'.")
|
|
134
|
+
else:
|
|
135
|
+
self.log(
|
|
136
|
+
f"Field '{key}' does not exist in hash '{hash_name}'.",
|
|
137
|
+
level="warning",
|
|
138
|
+
)
|
|
139
|
+
except Exception as e:
|
|
140
|
+
logger.error(f"Error deleting field '{key}' from hash '{hash_name}': {e}")
|
|
141
|
+
|
|
142
|
+
def read_all_hash(self, hash_name: str) -> dict | None:
|
|
143
|
+
"""
|
|
144
|
+
Reads all fields and values from a Redis hash.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
hash_name (str): Name of the hash in Redis.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
dict | None: A dictionary of all fields and values, or None if the hash does not exist.
|
|
151
|
+
"""
|
|
152
|
+
try:
|
|
153
|
+
hash_data = self.redis_client.hgetall(hash_name)
|
|
154
|
+
if hash_data:
|
|
155
|
+
items = {}
|
|
156
|
+
for key, value in hash_data.items():
|
|
157
|
+
value = value.decode()
|
|
158
|
+
try:
|
|
159
|
+
value = json.loads(value)
|
|
160
|
+
except json.JSONDecodeError:
|
|
161
|
+
pass
|
|
162
|
+
items[key.decode()] = value
|
|
163
|
+
|
|
164
|
+
self.log(f"Read all fields from hash '{hash_name}': {items}")
|
|
165
|
+
return items
|
|
166
|
+
else:
|
|
167
|
+
self.log(
|
|
168
|
+
f"Hash '{hash_name}' is empty or does not exist.", level="warning"
|
|
169
|
+
)
|
|
170
|
+
return None
|
|
171
|
+
except Exception as e:
|
|
172
|
+
logger.error(f"Error reading all fields from hash '{hash_name}': {e}")
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
def get_ttl(self, hash_name: str) -> int | None:
|
|
176
|
+
"""
|
|
177
|
+
Retrieves the remaining time-to-live (TTL) for a Redis hash.
|
|
178
|
+
|
|
179
|
+
Args:
|
|
180
|
+
hash_name (str): Name of the hash in Redis.
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
int | None: The remaining TTL in seconds, or None if the hash does not exist or has no TTL.
|
|
184
|
+
"""
|
|
185
|
+
try:
|
|
186
|
+
ttl = self.redis_client.ttl(hash_name)
|
|
187
|
+
if ttl == -1:
|
|
188
|
+
self.log(f"Hash '{hash_name}' has no TTL set.", level="warning")
|
|
189
|
+
elif ttl == -2:
|
|
190
|
+
self.log(f"Hash '{hash_name}' does not exist.", level="warning")
|
|
191
|
+
else:
|
|
192
|
+
self.log(f"TTL for hash '{hash_name}' is {ttl} seconds.")
|
|
193
|
+
return ttl
|
|
194
|
+
except Exception as e:
|
|
195
|
+
logger.error(f"Error retrieving TTL for hash '{hash_name}': {e}")
|
|
196
|
+
return None
|
|
197
|
+
|
|
198
|
+
def extend_ttl(self, hash_name: str, ttl: int) -> None:
|
|
199
|
+
"""
|
|
200
|
+
Extends or sets a new TTL for a Redis hash.
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
hash_name (str): Name of the hash in Redis.
|
|
204
|
+
ttl (int): New TTL in seconds.
|
|
205
|
+
"""
|
|
206
|
+
try:
|
|
207
|
+
if self.redis_client.exists(hash_name):
|
|
208
|
+
self.redis_client.expire(hash_name, ttl)
|
|
209
|
+
self.log(f"Extended TTL for hash '{hash_name}' to {ttl} seconds.")
|
|
210
|
+
else:
|
|
211
|
+
self.log(
|
|
212
|
+
f"Cannot set TTL because hash '{hash_name}' does not exist.",
|
|
213
|
+
level="warning",
|
|
214
|
+
)
|
|
215
|
+
except Exception as e:
|
|
216
|
+
logger.error(f"Error extending TTL for hash '{hash_name}': {e}")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pupsub import RedisPubSubManager
|