aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Leon Sandøy <[email protected]>2020-05-17 03:16:03 +0200
committerGravatar Leon Sandøy <[email protected]>2020-05-17 03:16:03 +0200
commit7cf0e83d1079ed34a3839948ce6823d95e0ebb62 (patch)
treea112a5d71f2ec69e321fc21b4411c99d0b0e553c
parentAdd fakeredis to the Pipfile (diff)
Implement .pop, .popitem and .setdefault.
Turns out the MutableMapping class doesn't give us servicable implementations of these, so we need to implement them ourselves. Also, let's not have keys returned as bytestrings.
-rw-r--r--bot/utils/redis_dict.py24
1 files changed, 22 insertions, 2 deletions
diff --git a/bot/utils/redis_dict.py b/bot/utils/redis_dict.py
index 35439b2f3..c89765a24 100644
--- a/bot/utils/redis_dict.py
+++ b/bot/utils/redis_dict.py
@@ -89,7 +89,8 @@ class RedisDict(MutableMapping):
def __iter__(self):
"""Iterate all the items in the Redis cache."""
- return iter(self._redis.hkeys(self._namespace))
+ keys = self._redis.hkeys(self._namespace)
+ return iter([key.decode('utf-8') for key in keys])
def __len__(self):
"""Return the number of items in the Redis cache."""
@@ -103,9 +104,28 @@ class RedisDict(MutableMapping):
"""Deletes the entire hash from the Redis cache."""
self._redis.delete(self._namespace)
- def get(self, key: ValidRedisKey, default: Optional[str] = None) -> JSONSerializableType:
+ def get(self, key: ValidRedisKey, default: Optional[JSONSerializableType] = None) -> JSONSerializableType:
"""Get the item, but provide a default if not found."""
if key in self:
return self[key]
else:
return default
+
+ def pop(self, key: ValidRedisKey, default: Optional[JSONSerializableType] = None) -> JSONSerializableType:
+ """Get the item, remove it from the cache, and provide a default if not found."""
+ value = self.get(key, default)
+ del self[key]
+ return value
+
+ def popitem(self) -> JSONSerializableType:
+ """Get the last item added to the cache."""
+ key = list(self.keys())[-1]
+ return self.pop(key)
+
+ def setdefault(self, key: ValidRedisKey, default: Optional[JSONSerializableType] = None) -> JSONSerializableType:
+ """Try to get the item. If the item does not exist, set it to `default` and return that."""
+ value = self.get(key)
+
+ if value is None:
+ self[key] = default
+ return default