redis-dict 2.6.0__py3-none-any.whl → 3.0.0__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- redis_dict/__init__.py +17 -0
- redis_dict.py → redis_dict/core.py +237 -299
- redis_dict/py.typed +0 -0
- redis_dict/type_management.py +273 -0
- {redis_dict-2.6.0.dist-info → redis_dict-3.0.0.dist-info}/METADATA +118 -34
- redis_dict-3.0.0.dist-info/RECORD +9 -0
- {redis_dict-2.6.0.dist-info → redis_dict-3.0.0.dist-info}/WHEEL +1 -1
- redis_dict-2.6.0.dist-info/RECORD +0 -6
- {redis_dict-2.6.0.dist-info → redis_dict-3.0.0.dist-info}/LICENSE +0 -0
- {redis_dict-2.6.0.dist-info → redis_dict-3.0.0.dist-info}/top_level.txt +0 -0
redis_dict/py.typed
ADDED
File without changes
|
@@ -0,0 +1,273 @@
|
|
1
|
+
"""Type management module."""
|
2
|
+
|
3
|
+
import json
|
4
|
+
import base64
|
5
|
+
from collections import OrderedDict, defaultdict
|
6
|
+
from datetime import datetime, date, time, timedelta
|
7
|
+
|
8
|
+
from typing import Callable, Any, Dict, Tuple, Set
|
9
|
+
|
10
|
+
from uuid import UUID
|
11
|
+
from decimal import Decimal
|
12
|
+
|
13
|
+
|
14
|
+
SENTINEL = object()
|
15
|
+
|
16
|
+
EncodeFuncType = Callable[[Any], str]
|
17
|
+
DecodeFuncType = Callable[[str], Any]
|
18
|
+
EncodeType = Dict[str, EncodeFuncType]
|
19
|
+
DecodeType = Dict[str, DecodeFuncType]
|
20
|
+
|
21
|
+
|
22
|
+
def _create_default_encode(custom_encode_method: str) -> EncodeFuncType:
|
23
|
+
def default_encode(obj: Any) -> str:
|
24
|
+
return getattr(obj, custom_encode_method)() # type: ignore[no-any-return]
|
25
|
+
return default_encode
|
26
|
+
|
27
|
+
|
28
|
+
def _create_default_decode(cls: type, custom_decode_method: str) -> DecodeFuncType:
|
29
|
+
def default_decode(encoded_str: str) -> Any:
|
30
|
+
return getattr(cls, custom_decode_method)(encoded_str)
|
31
|
+
return default_decode
|
32
|
+
|
33
|
+
|
34
|
+
def _decode_tuple(val: str) -> Tuple[Any, ...]:
|
35
|
+
"""
|
36
|
+
Deserialize a JSON-formatted string to a tuple.
|
37
|
+
|
38
|
+
This function takes a JSON-formatted string, deserializes it to a list, and
|
39
|
+
then converts the list to a tuple.
|
40
|
+
|
41
|
+
Args:
|
42
|
+
val (str): A JSON-formatted string representing a list.
|
43
|
+
|
44
|
+
Returns:
|
45
|
+
Tuple[Any, ...]: A tuple with the deserialized values from the input string.
|
46
|
+
"""
|
47
|
+
return tuple(json.loads(val))
|
48
|
+
|
49
|
+
|
50
|
+
def _encode_tuple(val: Tuple[Any, ...]) -> str:
|
51
|
+
"""
|
52
|
+
Serialize a tuple to a JSON-formatted string.
|
53
|
+
|
54
|
+
This function takes a tuple, converts it to a list, and then serializes
|
55
|
+
the list to a JSON-formatted string.
|
56
|
+
|
57
|
+
Args:
|
58
|
+
val (Tuple[Any, ...]): A tuple with values to be serialized.
|
59
|
+
|
60
|
+
Returns:
|
61
|
+
str: A JSON-formatted string representing the input tuple.
|
62
|
+
"""
|
63
|
+
return json.dumps(list(val))
|
64
|
+
|
65
|
+
|
66
|
+
def _decode_set(val: str) -> Set[Any]:
|
67
|
+
"""
|
68
|
+
Deserialize a JSON-formatted string to a set.
|
69
|
+
|
70
|
+
This function takes a JSON-formatted string, deserializes it to a list, and
|
71
|
+
then converts the list to a set.
|
72
|
+
|
73
|
+
Args:
|
74
|
+
val (str): A JSON-formatted string representing a list.
|
75
|
+
|
76
|
+
Returns:
|
77
|
+
set[Any]: A set with the deserialized values from the input string.
|
78
|
+
"""
|
79
|
+
return set(json.loads(val))
|
80
|
+
|
81
|
+
|
82
|
+
def _encode_set(val: Set[Any]) -> str:
|
83
|
+
"""
|
84
|
+
Serialize a set to a JSON-formatted string.
|
85
|
+
|
86
|
+
This function takes a set, converts it to a list, and then serializes the
|
87
|
+
list to a JSON-formatted string.
|
88
|
+
|
89
|
+
Args:
|
90
|
+
val (set[Any]): A set with values to be serialized.
|
91
|
+
|
92
|
+
Returns:
|
93
|
+
str: A JSON-formatted string representing the input set.
|
94
|
+
"""
|
95
|
+
return json.dumps(list(val))
|
96
|
+
|
97
|
+
|
98
|
+
decoding_registry: DecodeType = {
|
99
|
+
type('').__name__: str,
|
100
|
+
type(1).__name__: int,
|
101
|
+
type(0.1).__name__: float,
|
102
|
+
type(True).__name__: lambda x: x == "True",
|
103
|
+
type(None).__name__: lambda x: None,
|
104
|
+
|
105
|
+
"list": json.loads,
|
106
|
+
"dict": json.loads,
|
107
|
+
"tuple": _decode_tuple,
|
108
|
+
type(set()).__name__: _decode_set,
|
109
|
+
|
110
|
+
datetime.__name__: datetime.fromisoformat,
|
111
|
+
date.__name__: date.fromisoformat,
|
112
|
+
time.__name__: time.fromisoformat,
|
113
|
+
timedelta.__name__: lambda x: timedelta(seconds=float(x)),
|
114
|
+
|
115
|
+
Decimal.__name__: Decimal,
|
116
|
+
complex.__name__: lambda x: complex(*map(float, x.split(','))),
|
117
|
+
bytes.__name__: base64.b64decode,
|
118
|
+
|
119
|
+
UUID.__name__: UUID,
|
120
|
+
OrderedDict.__name__: lambda x: OrderedDict(json.loads(x)),
|
121
|
+
defaultdict.__name__: lambda x: defaultdict(type(None), json.loads(x)),
|
122
|
+
frozenset.__name__: lambda x: frozenset(json.loads(x)),
|
123
|
+
}
|
124
|
+
|
125
|
+
|
126
|
+
encoding_registry: EncodeType = {
|
127
|
+
"list": json.dumps,
|
128
|
+
"dict": json.dumps,
|
129
|
+
"tuple": _encode_tuple,
|
130
|
+
type(set()).__name__: _encode_set,
|
131
|
+
|
132
|
+
datetime.__name__: datetime.isoformat,
|
133
|
+
date.__name__: date.isoformat,
|
134
|
+
time.__name__: time.isoformat,
|
135
|
+
timedelta.__name__: lambda x: str(x.total_seconds()),
|
136
|
+
|
137
|
+
complex.__name__: lambda x: f"{x.real},{x.imag}",
|
138
|
+
bytes.__name__: lambda x: base64.b64encode(x).decode('ascii'),
|
139
|
+
OrderedDict.__name__: lambda x: json.dumps(list(x.items())),
|
140
|
+
defaultdict.__name__: lambda x: json.dumps(dict(x)),
|
141
|
+
frozenset.__name__: lambda x: json.dumps(list(x)),
|
142
|
+
}
|
143
|
+
|
144
|
+
|
145
|
+
class RedisDictJSONEncoder(json.JSONEncoder):
|
146
|
+
"""Extends JSON encoding capabilities by reusing RedisDict type conversion.
|
147
|
+
|
148
|
+
Uses existing decoding_registry to know which types to handle specially and
|
149
|
+
encoding_registry (falls back to str) for converting to JSON-compatible formats.
|
150
|
+
|
151
|
+
Example:
|
152
|
+
The encoded format looks like::
|
153
|
+
|
154
|
+
{
|
155
|
+
"__type__": "TypeName",
|
156
|
+
"value": <encoded value>
|
157
|
+
}
|
158
|
+
|
159
|
+
Notes:
|
160
|
+
|
161
|
+
Uses decoding_registry (containing all supported types) to check if type
|
162
|
+
needs special handling. For encoding, defaults to str() if no encoder exists
|
163
|
+
in encoding_registry.
|
164
|
+
"""
|
165
|
+
def default(self, o: Any) -> Any:
|
166
|
+
"""Overwrite default from json encoder.
|
167
|
+
|
168
|
+
Args:
|
169
|
+
o (Any): Object to be serialized.
|
170
|
+
|
171
|
+
Raises:
|
172
|
+
TypeError: If the object `o` cannot be serialized.
|
173
|
+
|
174
|
+
Returns:
|
175
|
+
Any: Serialized value.
|
176
|
+
"""
|
177
|
+
type_name = type(o).__name__
|
178
|
+
if type_name in decoding_registry:
|
179
|
+
return {
|
180
|
+
"__type__": type_name,
|
181
|
+
"value": encoding_registry.get(type_name, _default_encoder)(o)
|
182
|
+
}
|
183
|
+
try:
|
184
|
+
return json.JSONEncoder.default(self, o)
|
185
|
+
except TypeError as e:
|
186
|
+
raise TypeError(f"Object of type {type_name} is not JSON serializable") from e
|
187
|
+
|
188
|
+
|
189
|
+
class RedisDictJSONDecoder(json.JSONDecoder):
|
190
|
+
"""JSON decoder leveraging RedisDict existing type conversion system.
|
191
|
+
|
192
|
+
Works with RedisDictJSONEncoder to reconstruct Python objects from JSON using
|
193
|
+
RedisDict decoding_registry.
|
194
|
+
|
195
|
+
Still needs work but allows for more types than without.
|
196
|
+
"""
|
197
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
198
|
+
"""
|
199
|
+
Overwrite the __init__ method from JSON decoder.
|
200
|
+
|
201
|
+
Args:
|
202
|
+
*args (Any): Positional arguments for initialization.
|
203
|
+
**kwargs (Any): Keyword arguments for initialization.
|
204
|
+
|
205
|
+
"""
|
206
|
+
def _object_hook(obj: Dict[Any, Any]) -> Any:
|
207
|
+
if "__type__" in obj and "value" in obj:
|
208
|
+
type_name = obj["__type__"]
|
209
|
+
if type_name in decoding_registry:
|
210
|
+
return decoding_registry[type_name](obj["value"])
|
211
|
+
return obj
|
212
|
+
|
213
|
+
super().__init__(object_hook=_object_hook, *args, **kwargs)
|
214
|
+
|
215
|
+
|
216
|
+
def encode_json(obj: Any) -> str:
|
217
|
+
"""
|
218
|
+
Encode a Python object to a JSON string using the existing encoding registry.
|
219
|
+
|
220
|
+
Args:
|
221
|
+
obj (Any): The Python object to be encoded.
|
222
|
+
|
223
|
+
Returns:
|
224
|
+
str: The JSON-encoded string representation of the object.
|
225
|
+
"""
|
226
|
+
return json.dumps(obj, cls=RedisDictJSONEncoder)
|
227
|
+
|
228
|
+
|
229
|
+
def decode_json(s: str) -> Any:
|
230
|
+
"""
|
231
|
+
Decode a JSON string to a Python object using the existing decoding registry.
|
232
|
+
|
233
|
+
Args:
|
234
|
+
s (str): The JSON string to be decoded.
|
235
|
+
|
236
|
+
Returns:
|
237
|
+
Any: The decoded Python object.
|
238
|
+
"""
|
239
|
+
return json.loads(s, cls=RedisDictJSONDecoder)
|
240
|
+
|
241
|
+
|
242
|
+
def _default_decoder(x: str) -> str:
|
243
|
+
"""
|
244
|
+
Pass-through decoder that returns the input string unchanged.
|
245
|
+
|
246
|
+
Args:
|
247
|
+
x (str): The input string.
|
248
|
+
|
249
|
+
Returns:
|
250
|
+
str: The same input string.
|
251
|
+
"""
|
252
|
+
return x
|
253
|
+
|
254
|
+
|
255
|
+
def _default_encoder(x: Any) -> str:
|
256
|
+
"""
|
257
|
+
Takes x and returns the result str of the object.
|
258
|
+
|
259
|
+
Args:
|
260
|
+
x (Any): The input object
|
261
|
+
|
262
|
+
Returns:
|
263
|
+
str: output of str of the object
|
264
|
+
"""
|
265
|
+
return str(x)
|
266
|
+
|
267
|
+
|
268
|
+
encoding_registry["dict"] = encode_json
|
269
|
+
decoding_registry["dict"] = decode_json
|
270
|
+
|
271
|
+
|
272
|
+
encoding_registry["list"] = encode_json
|
273
|
+
decoding_registry["list"] = decode_json
|
@@ -1,13 +1,14 @@
|
|
1
1
|
Metadata-Version: 2.1
|
2
2
|
Name: redis-dict
|
3
|
-
Version:
|
3
|
+
Version: 3.0.0
|
4
4
|
Summary: Dictionary with Redis as storage backend
|
5
|
-
|
6
|
-
Author: Melvin Bijman
|
7
|
-
Author-email: bijman.m.m@gmail.com
|
5
|
+
Author-email: Melvin Bijman <bijman.m.m@gmail.com>
|
8
6
|
License: MIT
|
9
|
-
|
10
|
-
|
7
|
+
Project-URL: Homepage, https://github.com/Attumm/redisdict
|
8
|
+
Project-URL: Documentation, https://github.com/Attumm/redisdict#readme
|
9
|
+
Project-URL: Repository, https://github.com/Attumm/redisdict.git
|
10
|
+
Project-URL: Changelog, https://github.com/Attumm/redisdict/releases
|
11
|
+
Keywords: redis,python,dictionary,dict,key-value,database,caching,distributed-computing,dictionary-interface,large-datasets,scientific-computing,data-persistence,high-performance,scalable,pipelining,batching,big-data,data-types,distributed-algorithms,encryption,data-management
|
11
12
|
Classifier: Development Status :: 5 - Production/Stable
|
12
13
|
Classifier: Intended Audience :: Developers
|
13
14
|
Classifier: Intended Audience :: Information Technology
|
@@ -21,18 +22,51 @@ Classifier: Topic :: Software Development :: Object Brokering
|
|
21
22
|
Classifier: Topic :: Database :: Database Engines/Servers
|
22
23
|
Classifier: License :: OSI Approved :: MIT License
|
23
24
|
Classifier: Programming Language :: Python :: 3
|
24
|
-
Classifier: Programming Language :: Python :: 3.6
|
25
|
-
Classifier: Programming Language :: Python :: 3.7
|
26
25
|
Classifier: Programming Language :: Python :: 3.8
|
27
26
|
Classifier: Programming Language :: Python :: 3.9
|
28
27
|
Classifier: Programming Language :: Python :: 3.10
|
29
28
|
Classifier: Programming Language :: Python :: 3.11
|
30
29
|
Classifier: Programming Language :: Python :: 3.12
|
30
|
+
Classifier: Typing :: Typed
|
31
|
+
Requires-Python: >=3.8
|
31
32
|
Description-Content-Type: text/markdown
|
32
33
|
License-File: LICENSE
|
33
|
-
Requires-Dist: redis
|
34
|
+
Requires-Dist: redis>=4.0.0
|
35
|
+
Provides-Extra: dev
|
36
|
+
Requires-Dist: coverage==5.5; extra == "dev"
|
37
|
+
Requires-Dist: hypothesis==6.70.1; extra == "dev"
|
38
|
+
Requires-Dist: mypy>=1.8.0; extra == "dev"
|
39
|
+
Requires-Dist: mypy-extensions>=1.0.0; extra == "dev"
|
40
|
+
Requires-Dist: types-pyOpenSSL>=24.0.0.0; extra == "dev"
|
41
|
+
Requires-Dist: types-redis>=4.6.0; extra == "dev"
|
42
|
+
Requires-Dist: typing-extensions>=4.5.0; extra == "dev"
|
43
|
+
Requires-Dist: pylama>=8.4.1; extra == "dev"
|
44
|
+
Requires-Dist: pycodestyle==2.10.0; extra == "dev"
|
45
|
+
Requires-Dist: pydocstyle==6.3.0; extra == "dev"
|
46
|
+
Requires-Dist: pyflakes==3.0.1; extra == "dev"
|
47
|
+
Requires-Dist: pylint==3.2.7; extra == "dev"
|
48
|
+
Requires-Dist: mccabe==0.7.0; extra == "dev"
|
49
|
+
Requires-Dist: attrs==22.2.0; extra == "dev"
|
50
|
+
Requires-Dist: cffi==1.15.1; extra == "dev"
|
51
|
+
Requires-Dist: cryptography==43.0.1; extra == "dev"
|
52
|
+
Requires-Dist: exceptiongroup==1.1.1; extra == "dev"
|
53
|
+
Requires-Dist: future==0.18.3; extra == "dev"
|
54
|
+
Requires-Dist: pycparser==2.21; extra == "dev"
|
55
|
+
Requires-Dist: snowballstemmer==2.2.0; extra == "dev"
|
56
|
+
Requires-Dist: sortedcontainers==2.4.0; extra == "dev"
|
57
|
+
Requires-Dist: tomli==2.0.1; extra == "dev"
|
58
|
+
Requires-Dist: setuptools>=68.0.0; extra == "dev"
|
59
|
+
Requires-Dist: darglint; extra == "dev"
|
60
|
+
Requires-Dist: pydocstyle; extra == "dev"
|
61
|
+
Provides-Extra: docs
|
62
|
+
Requires-Dist: sphinx; extra == "docs"
|
63
|
+
Requires-Dist: sphinx-rtd-theme; extra == "docs"
|
64
|
+
Requires-Dist: sphinx-autodoc-typehints; extra == "docs"
|
65
|
+
Requires-Dist: tomli; extra == "docs"
|
66
|
+
Requires-Dist: myst-parser; extra == "docs"
|
34
67
|
|
35
68
|
# Redis-dict
|
69
|
+
[](https://pypi.org/project/redis-dict/)
|
36
70
|
[](https://github.com/Attumm/redis-dict/actions/workflows/ci.yml)
|
37
71
|
[](https://codecov.io/gh/Attumm/redis-dict)
|
38
72
|
[](https://pepy.tech/project/redis-dict)
|
@@ -44,7 +78,7 @@ The library includes utility functions for more complex use cases such as cachin
|
|
44
78
|
## Features
|
45
79
|
|
46
80
|
* Dictionary-like interface: Use familiar Python dictionary syntax to interact with Redis.
|
47
|
-
* Data Type Support: Comprehensive support for various data types
|
81
|
+
* Data Type Support: Comprehensive support for various data types.
|
48
82
|
* Pipelining support: Use pipelines for batch operations to improve performance.
|
49
83
|
* Expiration Support: Enables the setting of expiration times either globally or individually per key, through the use of context managers.
|
50
84
|
* Efficiency and Scalability: RedisDict is designed for use with large datasets and is optimized for efficiency. It retrieves only the data needed for a particular operation, ensuring efficient memory usage and fast performance.
|
@@ -86,7 +120,6 @@ In Redis our example looks like this.
|
|
86
120
|
|
87
121
|
### Namespaces
|
88
122
|
Acting as an identifier for your dictionary across different systems, RedisDict employs namespaces for organized data management. When a namespace isn't specified, "main" becomes the default. Thus allowing for data organization across systems and projects with the same redis instance.
|
89
|
-
|
90
123
|
This approach also minimizes the risk of key collisions between different applications, preventing hard-to-debug issues. By leveraging namespaces, RedisDict ensures a cleaner and more maintainable data management experience for developers working on multiple projects.
|
91
124
|
|
92
125
|
## Advanced Features
|
@@ -135,7 +168,6 @@ dic['gone'] = 'gone in 5 seconds'
|
|
135
168
|
Efficiently batch your requests using the Pipeline feature, which can be easily utilized with a context manager.
|
136
169
|
|
137
170
|
```python
|
138
|
-
from redis_dict import RedisDict
|
139
171
|
dic = RedisDict(namespace="example")
|
140
172
|
|
141
173
|
# one round trip to redis
|
@@ -253,16 +285,82 @@ print(dic["d"]) # Output: 4
|
|
253
285
|
For more advanced examples of RedisDict, please refer to the unit-test files in the repository. All features and functionalities are thoroughly tested in [unit tests (here)](https://github.com/Attumm/redis-dict/blob/main/tests.py#L1) Or take a look at load test for batching [load test](https://github.com/Attumm/redis-dict/blob/main/load_test.py#L1).
|
254
286
|
The unit-tests can be as used as a starting point.
|
255
287
|
|
256
|
-
|
288
|
+
## Types
|
289
|
+
|
290
|
+
### standard types
|
291
|
+
RedisDict supports a range of Python data types, from basic types to nested structures.
|
292
|
+
Basic types are handled natively, while complex data types like lists and dictionaries, RedisDict uses JSON serialization, specifically avoiding `pickle` due to its [security vulnerabilities](https://docs.python.org/3/library/pickle.html) in distributed computing contexts.
|
293
|
+
Although the library supports nested structures, the recommended best practice is to use RedisDict as a shallow dictionary.
|
294
|
+
This approach optimizes Redis database performance and efficiency by ensuring that each set and get operation efficiently maps to Redis's key-value storage capabilities, while still preserving the library's Pythonic interface.
|
295
|
+
Following types are supported:
|
296
|
+
`str, int, float, bool, NoneType, list, dict, tuple, set, datetime, date, time, timedelta, Decimal, complex, bytes, UUID, OrderedDict, defaultdict, frozenset`
|
297
|
+
```python
|
298
|
+
from uuid import UUID
|
299
|
+
from decimal import Decimal
|
300
|
+
from collections import OrderedDict, defaultdict
|
301
|
+
from datetime import datetime, date, time, timedelta
|
302
|
+
|
303
|
+
dic = RedisDict()
|
304
|
+
|
305
|
+
dic["string"] = "Hello World"
|
306
|
+
dic["number"] = 42
|
307
|
+
dic["float"] = 3.14
|
308
|
+
dic["bool"] = True
|
309
|
+
dic["None"] = None
|
310
|
+
|
311
|
+
dic["list"] = [1, 2, 3]
|
312
|
+
dic["dict"] = {"a": 1, "b": 2}
|
313
|
+
dic["tuple"] = (1, 2, 3)
|
314
|
+
dic["set"] = {1, 2, 3}
|
315
|
+
|
316
|
+
dic["datetime"] = datetime.date(2024, 1, 1, 12, 30, 45)
|
317
|
+
dic["date"] = date(2024, 1, 1)
|
318
|
+
dic["time"] = time(12, 30, 45)
|
319
|
+
dic["delta"] = timedelta(days=1, hours=2)
|
320
|
+
|
321
|
+
dic["decimal"] = Decimal("3.14159")
|
322
|
+
dic["complex"] = complex(1, 2)
|
323
|
+
dic["bytes"] = bytes([72, 101, 108, 108, 111])
|
324
|
+
dic["uuid"] = UUID('12345678-1234-5678-1234-567812345678')
|
325
|
+
|
326
|
+
dic["ordered"] = OrderedDict([('a', 1), ('b', 2)])
|
327
|
+
dic["default"] = defaultdict(int, {'a': 1, 'b': 2})
|
328
|
+
dic["frozen"] = frozenset([1, 2, 3])
|
329
|
+
```
|
330
|
+
|
331
|
+
|
332
|
+
|
333
|
+
### Nested types
|
334
|
+
Nested Types
|
335
|
+
RedisDict supports nested structures with mixed types through JSON serialization. The feature works by utilizing JSON encoding and decoding under the hood. While this represents an upgrade in functionality, the feature is not fully implemented and should be used with caution. For optimal performance, using shallow dictionaries is recommended.
|
336
|
+
```python
|
337
|
+
from datetime import datetime, timedelta
|
338
|
+
|
339
|
+
dic["mixed"] = [1, "foobar", 3.14, [1, 2, 3], datetime.now()]
|
340
|
+
|
341
|
+
dic['dic'] = {"elapsed_time": timedelta(hours=60)}
|
342
|
+
```
|
343
|
+
|
344
|
+
### JSON Encoding - Decoding
|
345
|
+
The nested type support in RedisDict is implemented using custom JSON encoders and decoders. These JSON encoders and decoders are built on top of RedisDict's own encoding and decoding functionality, extending it for JSON compatibility. Since JSON serialization was a frequently requested feature, these enhanced encoders and decoders are available for use in other projects:
|
346
|
+
```python
|
347
|
+
import json
|
348
|
+
from datetime import datetime
|
349
|
+
from redis_dict import RedisDictJSONDecoder, RedisDictJSONEncoder
|
350
|
+
|
351
|
+
data = [1, "foobar", 3.14, [1, 2, 3], datetime.now()]
|
352
|
+
encoded = json.dumps(data, cls=RedisDictJSONEncoder)
|
353
|
+
result = json.loads(encoded, cls=RedisDictJSONDecoder)
|
354
|
+
```
|
355
|
+
|
257
356
|
|
258
|
-
|
357
|
+
### Extending RedisDict with Custom Types
|
259
358
|
|
260
359
|
RedisDict supports custom type serialization. Here's how to add a new type:
|
261
360
|
|
262
361
|
|
263
362
|
```python
|
264
363
|
import json
|
265
|
-
from redis_dict import RedisDict
|
266
364
|
|
267
365
|
class Person:
|
268
366
|
def __init__(self, name, age):
|
@@ -291,23 +389,13 @@ assert result.name == person.name
|
|
291
389
|
assert result.age == person.age
|
292
390
|
```
|
293
391
|
|
294
|
-
|
295
|
-
>>> from datetime import datetime
|
296
|
-
>>> redis_dict.extends_type(datetime, datetime.isoformat, datetime.fromisoformat)
|
297
|
-
>>> redis_dict["now"] = datetime.now()
|
298
|
-
>>> redis_dict
|
299
|
-
{'now': datetime.datetime(2024, 10, 14, 18, 41, 53, 493775)}
|
300
|
-
>>> redis_dict["now"]
|
301
|
-
datetime.datetime(2024, 10, 14, 18, 41, 53, 493775)
|
302
|
-
```
|
303
|
-
|
304
|
-
For more information on [extending types](https://github.com/Attumm/redis-dict/blob/main/extend_types_tests.py).
|
392
|
+
For more information on [extending types](https://github.com/Attumm/redis-dict/blob/main/tests/unit/extend_types_tests.py).
|
305
393
|
### Redis Encryption
|
306
394
|
Setup guide for configuring and utilizing encrypted Redis TLS for redis-dict.
|
307
|
-
[Setup guide](https://github.com/Attumm/redis-dict/blob/main/encrypted_redis.MD)
|
395
|
+
[Setup guide](https://github.com/Attumm/redis-dict/blob/main/docs/tutorials/encrypted_redis.MD)
|
308
396
|
|
309
397
|
### Redis Storage Encryption
|
310
|
-
For storing encrypted data values, it's possible to use extended types. Take a look at this [encrypted test](https://github.com/Attumm/redis-dict/blob/main/encrypt_tests.py).
|
398
|
+
For storing encrypted data values, it's possible to use extended types. Take a look at this [encrypted test](https://github.com/Attumm/redis-dict/blob/main/tests/unit/encrypt_tests.py).
|
311
399
|
|
312
400
|
### Tests
|
313
401
|
The RedisDict library includes a comprehensive suite of tests that ensure its correctness and resilience. The test suite covers various data types, edge cases, and error handling scenarios. It also employs the Hypothesis library for property-based testing, which provides fuzz testing to evaluate the implementation
|
@@ -315,19 +403,16 @@ The RedisDict library includes a comprehensive suite of tests that ensure its co
|
|
315
403
|
### Redis config
|
316
404
|
To configure RedisDict using your Redis config.
|
317
405
|
|
318
|
-
Configure both the host and port.
|
406
|
+
Configure both the host and port. Or configuration with a setting dictionary.
|
319
407
|
```python
|
320
408
|
dic = RedisDict(host='127.0.0.1', port=6380)
|
321
|
-
```
|
322
409
|
|
323
|
-
Configuration with a dictionary.
|
324
|
-
```python
|
325
410
|
redis_config = {
|
326
411
|
'host': '127.0.0.1',
|
327
412
|
'port': 6380,
|
328
413
|
}
|
329
414
|
|
330
|
-
|
415
|
+
confid_dic = RedisDict(**redis_config)
|
331
416
|
```
|
332
417
|
|
333
418
|
## Installation
|
@@ -338,4 +423,3 @@ pip install redis-dict
|
|
338
423
|
### Note
|
339
424
|
* Please be aware that this project is currently being utilized by various organizations in their production environments. If you have any questions or concerns, feel free to raise issues
|
340
425
|
* This project only uses redis as dependency
|
341
|
-
|
@@ -0,0 +1,9 @@
|
|
1
|
+
redis_dict/__init__.py,sha256=fksonUr5DetzwFDEkT7lpmAaV3Jhmp2IQ12t62LwFb4,476
|
2
|
+
redis_dict/core.py,sha256=iLVTzpR4HmMPqcgZQWMgdAgwRepLEhTbdxP-tfA13ts,34698
|
3
|
+
redis_dict/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
4
|
+
redis_dict/type_management.py,sha256=U3aP_EtHByApRdHvpr-zSOjok6r9BVZ0g3YnpVCVt8Y,7690
|
5
|
+
redis_dict-3.0.0.dist-info/LICENSE,sha256=-QiLwYznh_vNUSz337k0faP9Jl0dgtCIHVZ39Uyl6cA,1070
|
6
|
+
redis_dict-3.0.0.dist-info/METADATA,sha256=8Zn6a75THLjxiCGfRdFuz675RwSsLrBf0JQE8fH-Kfo,16873
|
7
|
+
redis_dict-3.0.0.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
|
8
|
+
redis_dict-3.0.0.dist-info/top_level.txt,sha256=Wyp5Xvq_imoxvu-c-Le1rbTZ3pYM5BF440H9YAcgBZ8,11
|
9
|
+
redis_dict-3.0.0.dist-info/RECORD,,
|
@@ -1,6 +0,0 @@
|
|
1
|
-
redis_dict.py,sha256=50CSZ5dMBBbr-UU9BSvoGgBItD7uce8F5ty1lphaiUw,36901
|
2
|
-
redis_dict-2.6.0.dist-info/LICENSE,sha256=-QiLwYznh_vNUSz337k0faP9Jl0dgtCIHVZ39Uyl6cA,1070
|
3
|
-
redis_dict-2.6.0.dist-info/METADATA,sha256=6QJ93NO1RrVKSYbmbgtFKOazqtKrauPstB-H0hI1vDs,12564
|
4
|
-
redis_dict-2.6.0.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
|
5
|
-
redis_dict-2.6.0.dist-info/top_level.txt,sha256=Wyp5Xvq_imoxvu-c-Le1rbTZ3pYM5BF440H9YAcgBZ8,11
|
6
|
-
redis_dict-2.6.0.dist-info/RECORD,,
|
File without changes
|
File without changes
|