-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkey_value_redis.py
91 lines (66 loc) · 2.59 KB
/
key_value_redis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""TcEx Framework Module"""
# third-party
from redis import Redis
from .key_value_abc import KeyValueABC
class KeyValueRedis(KeyValueABC):
"""TcEx Key Value Redis Module.
Args:
redis_client (redis.Client): An instance of redis client.
"""
def __init__(self, redis_client: Redis):
"""Initialize the Class properties."""
self.redis_client = redis_client
# properties
self.kv_type = 'redis'
def create(self, context: str, key: str, value: bytes | str) -> int:
"""Create key/value pair in Redis.
Args:
context: A specific context for the create.
key: The field name (key) for the kv pair in Redis.
value: The value for the kv pair in Redis.
Returns:
str: The number of fields that were added.
"""
return self.redis_client.hset(context, key, value)
def delete(self, context: str, key: str) -> int:
"""Alias for hdel method.
Args:
context: A specific context for the create.
key: The field name (key) for the kv pair in Redis.
Returns:
str: The response from Redis.
"""
return self.redis_client.hdel(context, key)
def get_all(self, context: str) -> dict[str, bytes | str | None]:
"""Return the contents for a given context.
Args:
context: the context to return
"""
return self.hgetall(context)
def hgetall(self, context: str) -> dict[str, bytes | str | None]:
"""Read data from Redis for the current context.
Args:
context: A specific context for the create.
Returns:
list: The response data from Redis.
"""
return self.redis_client.hgetall(context)
def read(self, context: str, key: str) -> bytes | str | None:
"""Read data from Redis for the provided key.
Args:
context: A specific context for the create.
key: The field name (key) for the kv pair in Redis.
Returns:
str: The response data from Redis.
"""
return self.hget(context, key)
def hget(self, context: str, key: str) -> bytes | str | None:
"""Read data from redis for the provided key.
This method will *not* convert the retrieved data (like read() does).
Args:
context: A specific context for the create.
key: The field name (key) for the kv pair in Redis.
Returns:
bytes | None: the raw value from redis, if any
"""
return self.redis_client.hget(context, key)