def get(self, key, default=None, timeout=None): """ Get a value from the storage. :param key: The key of the requested storage value :param default: The value that's returned if the requested key doesn't exist. Defaults to None. :param timeout: Give up cache writing after a specific time """ value = self.cache.get('storage/' + key) if value is not None: return value result = db.session.execute( db.select([Storage.value]).where(Storage.key == key)).fetchone() if result is None: return default value = result[0] self._update_cache(key, value, timeout) return value
def get_many(self, keys, timeout=None): """ Get many cached values with just one cache hit or database query. :param keys: A list of the requested keys :param timeout: Give up cache writing after a specific time """ objects = self.cache.get_dict(*('storage/%s' % key for key in keys)) values = {} for key, value in objects.iteritems(): values[key[8:]] = value #: a list of keys that aren't yet in the cache. #: They are queried using a database call. to_fetch = [k for k in keys if values.get(k) is None] if to_fetch: # get the items that are not in cache using a database query query = db.select([Storage.key, Storage.value]) \ .where(Storage.key.in_(to_fetch)) for key, value in db.session.execute(query): values[key] = value self._update_cache(key, value, timeout) return values
def get(self, key, default=None, timeout=None): """ Get a value from the storage. :param key: The key of the requested storage value :param default: The value that's returned if the requested key doesn't exist. Defaults to None. :param timeout: Give up cache writing after a specific time """ value = self.cache.get('storage/' + key) if value is not None: return value result = db.session.execute( db.select([Storage.value]).where(Storage.key == key) ).fetchone() if result is None: return default value = result[0] self._update_cache(key, value, timeout) return value