redis-dict 2.7.0__py3-none-any.whl → 3.1.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
redis_dict/py.typed ADDED
File without changes
@@ -0,0 +1,276 @@
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
+ """
147
+ Extends JSON encoding capabilities by reusing RedisDict type conversion.
148
+
149
+ Uses existing decoding_registry to know which types to handle specially and
150
+ encoding_registry (falls back to str) for converting to JSON-compatible formats.
151
+
152
+ Example:
153
+ The encoded format looks like::
154
+
155
+ {
156
+ "__type__": "TypeName",
157
+ "value": <encoded value>
158
+ }
159
+
160
+ Notes:
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
+
166
+ def default(self, o: Any) -> Any:
167
+ """Overwrite default from json encoder.
168
+
169
+ Args:
170
+ o (Any): Object to be serialized.
171
+
172
+ Raises:
173
+ TypeError: If the object `o` cannot be serialized.
174
+
175
+ Returns:
176
+ Any: Serialized value.
177
+ """
178
+ type_name = type(o).__name__
179
+ if type_name in decoding_registry:
180
+ return {
181
+ "__type__": type_name,
182
+ "value": encoding_registry.get(type_name, _default_encoder)(o)
183
+ }
184
+ try:
185
+ return json.JSONEncoder.default(self, o)
186
+ except TypeError as e:
187
+ raise TypeError(f"Object of type {type_name} is not JSON serializable") from e
188
+
189
+
190
+ class RedisDictJSONDecoder(json.JSONDecoder):
191
+ """
192
+ JSON decoder leveraging RedisDict existing type conversion system.
193
+
194
+ Works with RedisDictJSONEncoder to reconstruct Python objects from JSON using
195
+ RedisDict decoding_registry.
196
+
197
+ Still needs work but allows for more types than without.
198
+ """
199
+
200
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
201
+ """
202
+ Overwrite the __init__ method from JSON decoder.
203
+
204
+ Args:
205
+ *args (Any): Positional arguments for initialization.
206
+ **kwargs (Any): Keyword arguments for initialization.
207
+
208
+ """
209
+ def _object_hook(obj: Dict[Any, Any]) -> Any:
210
+ if "__type__" in obj and "value" in obj:
211
+ type_name = obj["__type__"]
212
+ if type_name in decoding_registry:
213
+ return decoding_registry[type_name](obj["value"])
214
+ return obj
215
+
216
+ super().__init__(object_hook=_object_hook, *args, **kwargs)
217
+
218
+
219
+ def encode_json(obj: Any) -> str:
220
+ """
221
+ Encode a Python object to a JSON string using the existing encoding registry.
222
+
223
+ Args:
224
+ obj (Any): The Python object to be encoded.
225
+
226
+ Returns:
227
+ str: The JSON-encoded string representation of the object.
228
+ """
229
+ return json.dumps(obj, cls=RedisDictJSONEncoder)
230
+
231
+
232
+ def decode_json(s: str) -> Any:
233
+ """
234
+ Decode a JSON string to a Python object using the existing decoding registry.
235
+
236
+ Args:
237
+ s (str): The JSON string to be decoded.
238
+
239
+ Returns:
240
+ Any: The decoded Python object.
241
+ """
242
+ return json.loads(s, cls=RedisDictJSONDecoder)
243
+
244
+
245
+ def _default_decoder(x: str) -> str:
246
+ """
247
+ Pass-through decoder that returns the input string unchanged.
248
+
249
+ Args:
250
+ x (str): The input string.
251
+
252
+ Returns:
253
+ str: The same input string.
254
+ """
255
+ return x
256
+
257
+
258
+ def _default_encoder(x: Any) -> str:
259
+ """
260
+ Take x and returns the result str of the object.
261
+
262
+ Args:
263
+ x (Any): The input object
264
+
265
+ Returns:
266
+ str: output of str of the object
267
+ """
268
+ return str(x)
269
+
270
+
271
+ encoding_registry["dict"] = encode_json
272
+ decoding_registry["dict"] = decode_json
273
+
274
+
275
+ encoding_registry["list"] = encode_json
276
+ decoding_registry["list"] = decode_json
@@ -1,13 +1,14 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: redis-dict
3
- Version: 2.7.0
3
+ Version: 3.1.0
4
4
  Summary: Dictionary with Redis as storage backend
5
- Home-page: https://github.com/Attumm/redisdict
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
- Keywords: redis python dictionary dict key-value 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
10
- Platform: any
7
+ Project-URL: Homepage, https://github.com/Attumm/redisdict
8
+ Project-URL: Documentation, https://attumm.github.io/redis-dict/
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
+ [![PyPI](https://img.shields.io/pypi/v/redis-dict.svg)](https://pypi.org/project/redis-dict/)
36
70
  [![CI](https://github.com/Attumm/redis-dict/actions/workflows/ci.yml/badge.svg)](https://github.com/Attumm/redis-dict/actions/workflows/ci.yml)
37
71
  [![codecov](https://codecov.io/gh/Attumm/redis-dict/graph/badge.svg?token=Lqs7McQGEs)](https://codecov.io/gh/Attumm/redis-dict)
38
72
  [![Downloads](https://static.pepy.tech/badge/redis-dict/month)](https://pepy.tech/project/redis-dict)
@@ -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
@@ -263,14 +295,11 @@ This approach optimizes Redis database performance and efficiency by ensuring th
263
295
  Following types are supported:
264
296
  `str, int, float, bool, NoneType, list, dict, tuple, set, datetime, date, time, timedelta, Decimal, complex, bytes, UUID, OrderedDict, defaultdict, frozenset`
265
297
  ```python
266
- from redis_dict import RedisDict
267
-
268
298
  from uuid import UUID
269
299
  from decimal import Decimal
270
300
  from collections import OrderedDict, defaultdict
271
301
  from datetime import datetime, date, time, timedelta
272
302
 
273
-
274
303
  dic = RedisDict()
275
304
 
276
305
  dic["string"] = "Hello World"
@@ -299,6 +328,32 @@ dic["default"] = defaultdict(int, {'a': 1, 'b': 2})
299
328
  dic["frozen"] = frozenset([1, 2, 3])
300
329
  ```
301
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
+
356
+
302
357
  ### Extending RedisDict with Custom Types
303
358
 
304
359
  RedisDict supports custom type serialization. Here's how to add a new type:
@@ -306,7 +361,6 @@ RedisDict supports custom type serialization. Here's how to add a new type:
306
361
 
307
362
  ```python
308
363
  import json
309
- from redis_dict import RedisDict
310
364
 
311
365
  class Person:
312
366
  def __init__(self, name, age):
@@ -335,23 +389,13 @@ assert result.name == person.name
335
389
  assert result.age == person.age
336
390
  ```
337
391
 
338
- ```python
339
- >>> from datetime import datetime
340
- >>> redis_dict.extends_type(datetime, datetime.isoformat, datetime.fromisoformat)
341
- >>> redis_dict["now"] = datetime.now()
342
- >>> redis_dict
343
- {'now': datetime.datetime(2024, 10, 14, 18, 41, 53, 493775)}
344
- >>> redis_dict["now"]
345
- datetime.datetime(2024, 10, 14, 18, 41, 53, 493775)
346
- ```
347
-
348
- 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).
349
393
  ### Redis Encryption
350
394
  Setup guide for configuring and utilizing encrypted Redis TLS for redis-dict.
351
- [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)
352
396
 
353
397
  ### Redis Storage Encryption
354
- 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).
355
399
 
356
400
  ### Tests
357
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
@@ -359,19 +403,16 @@ The RedisDict library includes a comprehensive suite of tests that ensure its co
359
403
  ### Redis config
360
404
  To configure RedisDict using your Redis config.
361
405
 
362
- Configure both the host and port.
406
+ Configure both the host and port. Or configuration with a setting dictionary.
363
407
  ```python
364
408
  dic = RedisDict(host='127.0.0.1', port=6380)
365
- ```
366
409
 
367
- Configuration with a dictionary.
368
- ```python
369
410
  redis_config = {
370
411
  'host': '127.0.0.1',
371
412
  'port': 6380,
372
413
  }
373
414
 
374
- dic = RedisDict(**redis_config)
415
+ confid_dic = RedisDict(**redis_config)
375
416
  ```
376
417
 
377
418
  ## Installation
@@ -382,4 +423,3 @@ pip install redis-dict
382
423
  ### Note
383
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
384
425
  * This project only uses redis as dependency
385
-
@@ -0,0 +1,9 @@
1
+ redis_dict/__init__.py,sha256=fksonUr5DetzwFDEkT7lpmAaV3Jhmp2IQ12t62LwFb4,476
2
+ redis_dict/core.py,sha256=ej7_EfkPIIb0gH_Ndpeue4i-WsNFGuw0dV6fNm-drzY,34352
3
+ redis_dict/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ redis_dict/type_management.py,sha256=ruyqswKqfte_G-ClTlV6ZuTmrTVkSsHFCy9LEdgblac,7700
5
+ redis_dict-3.1.0.dist-info/LICENSE,sha256=-QiLwYznh_vNUSz337k0faP9Jl0dgtCIHVZ39Uyl6cA,1070
6
+ redis_dict-3.1.0.dist-info/METADATA,sha256=wq3vcKRqTgUllyhm8oEogx9ikHCa6UT4kLNw86bfm3c,16867
7
+ redis_dict-3.1.0.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
8
+ redis_dict-3.1.0.dist-info/top_level.txt,sha256=Wyp5Xvq_imoxvu-c-Le1rbTZ3pYM5BF440H9YAcgBZ8,11
9
+ redis_dict-3.1.0.dist-info/RECORD,,
@@ -1,6 +0,0 @@
1
- redis_dict.py,sha256=LmP5C1lIf3KCG_3pfcnw3CZE5KuUUym2U_UqlbFoiVg,38214
2
- redis_dict-2.7.0.dist-info/LICENSE,sha256=-QiLwYznh_vNUSz337k0faP9Jl0dgtCIHVZ39Uyl6cA,1070
3
- redis_dict-2.7.0.dist-info/METADATA,sha256=8SDlje1sUiquUlKvk27LHRhLTsdwr9b5KTsKBa5XhGk,14300
4
- redis_dict-2.7.0.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
5
- redis_dict-2.7.0.dist-info/top_level.txt,sha256=Wyp5Xvq_imoxvu-c-Le1rbTZ3pYM5BF440H9YAcgBZ8,11
6
- redis_dict-2.7.0.dist-info/RECORD,,