Created
October 21, 2019 01:19
-
-
Save MinweiShen/7644ece0aa63605e50e9cce5ccdc29ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Cache(): | |
def __init__(self): | |
self._cache = { | |
'_index': {} | |
} | |
def set(self, key, value): | |
self._cache[key] = value | |
self.index(key) | |
def get(self, key): | |
return self._cache.get(key, None) | |
def delete(self, key): | |
try: | |
del self._cache[key] | |
self.un_index(key) | |
except: | |
pass | |
def delete_group(self, group_key): | |
keys = group_key.split(':') | |
index = self._cache['_index'] | |
prev = index | |
try: | |
for k in keys: | |
prev = index | |
index = index[k] | |
prev[keys[-1]] = {} | |
self._clean(index, group_key) | |
except: | |
pass | |
def _clean(self, index, key): | |
if not index.keys(): | |
self.delete(key) | |
else: | |
for k in index.keys(): | |
self._clean(index[k], key + ':' + k) | |
def un_index(self, key): | |
keys = key.split(':') | |
index = self._cache['_index'] | |
for k in keys[:-1]: | |
index = index[k] | |
del index[keys[-1]] | |
def index(self, key): | |
keys = key.split(':') | |
index = self._cache['_index'] | |
for k in keys: | |
index = index.setdefault(k, {}) | |
def display(self): | |
print self._cache | |
cache = Cache() | |
cache.set('HBO:filters:adv', [1,2]) | |
cache.set('HBO:filters:all', [1,2,3,4]) | |
cache.display() | |
cache.delete('HBO:filters:all') | |
cache.display() | |
cache.delete_group('HBO') | |
cache.display() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment