def main(): client = Client(('localhost', 11211)) client.set('some_key', 'some_value') client.set('some_key1', 'some_value') client.set('some_key2', 'some_value') client.set('some_key3', 'some_value') client.set('some_key4', 'some_value') # client.set('some_key1', { "a": 3, "b": 1234, "c": 1234567 }) # result = client.get('some_key') # client.set('some_key2', { "a": 3, "b": 1234, "c": 1234567 }) # result = client.get('some_key') # client.set('some_key3', { "a": 3, "b": 1234, "c": 1234567 }) # result = client.get('some_key') # print (result) result = client.get_multi(['some_key2', 'some_key3']) print(result) print(client.delete('some_key')) print(client.get('some_key')) client.set('new', 'unknown value') client.set('test1', 'tesing unknow reasonable text') client.set('test2', 'although i know it will be hash value') client.set('test3', 'show me the value') client.set('test4', 'whatever it takes') client.set('test5', 'something at works') return True
class Dao: def __init__(self, host, port): self.db = Client((host, port), default_noreply=False, serializer=self.__json_serializer, deserializer=self.__json_deserializer) def __json_serializer(self, key, value): if type(value) == str: return value, 1 return json.dumps(value), 2 def __json_deserializer(self, key, value, flags): if flags == 1: return value.decode('utf-8') if flags == 2: return json.loads(value.decode('utf-8')) raise Exception('Unknown serialization format') def get_osushi(self, id): osushi = self.db.get(f'osushi:{id}') return osushi def get_osushi_list(self, start_id, n): osushi_list = [] for i in range(n): id = start_id - i osushi = self.db.get(f'osushi:{id}') if osushi is None: break osushi_list.append({'id': id, **osushi}) return osushi_list def get_all_osushi(self): count = self.get_osushi_count() ids = range(1, count + 1) result = self.db.get_multi([f'osushi:{id}' for id in ids]) return [{'id': id, **result[f'osushi:{id}']} for id in ids] def get_osushi_count(self): count = self.db.get('osushi:count') return count if count else 0 def set_osushi(self, id, osushi): if type(osushi) is sushi.Sushi: osushi = dataclasses.asdict(osushi) self.db.set(f'osushi:{id}', osushi) def incr_osushi_count(self): count = self.db.get('osushi:count') if count: return self.db.incr('osushi:count', 1) else: self.db.set('osushi:count', 1) return 1 def is_first_time(self, address): key = f'visited:{address}' result = self.db.get(key) if result is None: return True return False def visit_user(self, address): key = f'visited:{address}' self.db.set(key, True)
class MemcachedAdapter(BaseAdapter): """ Exposes a cache store using Memcached. Exposes `pymemcache`'s exceptions. """ def __init__(self, host='localhost', port=11211, **kwargs): super().__init__() self.store = Client((host, port), **kwargs) def set(self, key, value, ttl): if ttl == -1: ttl = 0 return self.store.set(key, value, expire=ttl) def batch_set(self, keys, values, ttls): # There's two reasons to recode pymemcache.set_multi(): # - It returns a list of keys that failed to be inserted, and the base expects a boolean # - It only allows a unique ttl for all keys commands = [] ttls = [0 if ttl == -1 else ttl for ttl in ttls] for key, value, ttl in zip(keys, values, ttls): ttl = self.store._check_integer(ttl, 'expire') # pylint: disable=protected-access key = self.store.check_key(key) value, flags = self.store.serde.serialize(key, value) command = b'set ' + key command += b' ' + str(flags).encode(self.store.encoding) command += b' ' + ttl command += b' ' + str(len(value)).encode( self.store.encoding) + b'\r\n' command += value.encode(self.store.encoding) + b'\r\n' commands.append(command) results = self.store._misc_cmd(commands, 'set', False) # pylint: disable=protected-access for line in results: if line == b'NOT_STORED': return False return True def get(self, key): value = self.store.get(key) return value def batch_get(self, keys): key_to_value = self.store.get_multi(keys) values = [ key_to_value[key] if key in key_to_value else None for key in keys ] return values def delete(self, key): return self.store.delete(key, noreply=False) def batch_delete(self, keys): # Here as well, pymemcache.delete_multi() always returns True commands = [] for key in keys: key = self.store.check_key(key) command = b'delete ' + key + b'\r\n' commands.append(command) results = self.store._misc_cmd(commands, 'delete', False) # pylint: disable=protected-access for line in results: print(f"\"{line}\"") if line == b'NOT_FOUND': return False return True def exists(self, key): # Can't just cast to bool since we can store falsey values return self.store.get(key) is not None def flush(self): return self.store.flush_all(noreply=False) def ping(self): return bool(self.store.stats()) @property def connection_exceptions(self): return (MemcacheUnexpectedCloseError, MemcacheServerError, MemcacheUnknownError)