summaryrefslogtreecommitdiff
path: root/lib/utils/cache.py
diff options
context:
space:
mode:
authorLex Neva <github.com@lexneva.name>2022-07-21 23:16:56 -0400
committerLex Neva <github.com@lexneva.name>2023-02-18 22:34:16 -0500
commitd51feec98d7b4e4b224c34c013da6df059b78005 (patch)
treee96f12b49c3b711c2460ee2f2b4fd4244c7fe954 /lib/utils/cache.py
parent44af368c795c2c469eb09fee884675db17b7d6d6 (diff)
cache key generation using params, path, color, and style
Diffstat (limited to 'lib/utils/cache.py')
-rw-r--r--lib/utils/cache.py37
1 files changed, 37 insertions, 0 deletions
diff --git a/lib/utils/cache.py b/lib/utils/cache.py
index 46d8ec59..767978ca 100644
--- a/lib/utils/cache.py
+++ b/lib/utils/cache.py
@@ -4,6 +4,8 @@
# Licensed under the GNU GPL version 3.0 or later. See the file LICENSE for details.
import os
import atexit
+import hashlib
+import pickle
import appdirs
import diskcache
@@ -31,3 +33,38 @@ def get_stitch_plan_cache():
atexit.register(__stitch_plan_cache.close)
return __stitch_plan_cache
+
+
+class CacheKeyGenerator(object):
+ """Generate cache keys given arbitrary data.
+
+ Given arbitrary data, generate short cache key that is extremely likely
+ to be unique.
+
+ Use example:
+
+ >>> generator = CacheKeyGenerator()
+ >>> generator.update(b'12345')
+ >>> generator.update([1, 2, 3, {4, 5, 6}])
+ >>> generator.get_cache_key()
+ """
+
+ def __init__(self):
+ # SHA1 is chosen for speed. We don't need cryptography-grade hashing
+ # for this use case.
+ self._hasher = hashlib.sha1()
+
+ def update(self, data):
+ """Provide data to be hashed into a cache key.
+
+ Arguments:
+ data -- a bytes object or any object that can be pickled
+ """
+
+ if not isinstance(data, bytes):
+ data = pickle.dumps(data)
+
+ self._hasher.update(data)
+
+ def get_cache_key(self):
+ return self._hasher.hexdigest()