Allow get() on new values in Cache()

Previously, it was only possible to access already-cached values via Cache.get(), this restriction is now gone. Also, data is now kept raw (not base64). It's also possible from now on to pass the type of var wanted (such as int).
master
pictuga 2013-11-03 20:18:43 +01:00
parent 22d12a769c
commit f52e2871ac
1 changed files with 10 additions and 7 deletions

View File

@ -130,30 +130,33 @@ class Cache:
for line in data: for line in data:
if "\t" in line: if "\t" in line:
key, bdata = line.split("\t", 1) key, bdata = line.split("\t", 1)
self._cached[key] = bdata self._cached[key] = b64decode(bdata)
def __del__(self): def __del__(self):
self.save() self.save()
def __contains__(self, key): def __contains__(self, key):
return key in self._cached return key in self._cache or key in self._cached
def get(self, key): def get(self, key, kind=str):
if key in self._cached: if key in self._cache:
return kind(self._cache[key])
elif key in self._cached:
self._cache[key] = self._cached[key] self._cache[key] = self._cached[key]
return b64decode(self._cached[key]) return kind(self._cached[key])
else: else:
return None return None
def set(self, key, content): def set(self, key, content):
self._cache[key] = b64encode(str(content) or '') self._cache[key] = str(content) or ''
def save(self): def save(self):
if len(self._cache) == 0: if len(self._cache) == 0:
return return
out = [] out = []
for (key, bdata) in self._cache.iteritems(): for (key, data) in self._cache.iteritems():
bdata = b64encode(data)
out.append(str(key) + "\t" + bdata) out.append(str(key) + "\t" + bdata)
txt = "\n".join(out) txt = "\n".join(out)