async def traced_yaaredis(): r = yaaredis.StrictRedis(port=REDIS_CONFIG["port"]) await r.flushall() patch() try: yield r finally: unpatch() r = yaaredis.StrictRedis(port=REDIS_CONFIG["port"]) await r.flushall()
async def example(): client = yaaredis.StrictRedis() # pay attention that async_generator don't need to be awaited keys = client.scan_iter() # use `async for` instead of `for` only async for key in keys: print(key)
async def test_read_only_error(event_loop): """ READONLY errors get turned in ReadOnlyError exceptions """ client = yaaredis.StrictRedis(loop=event_loop) with pytest.raises(ReadOnlyError): await client.execute_command('DEBUG', 'ERROR', 'READONLY blah blah')
async def aio_child(): redis = yaaredis.StrictRedis(host='127.0.0.1', port=6379, db=0) await redis.flushdb() await redis.set('bar', 'foo') resp = await redis.get('bar') return resp
async def use_pubsub_in_thread(): client = yaaredis.StrictRedis() pubsub = client.pubsub() await pubsub.subscribe(**{'my-channel': my_handler}) thread = pubsub.run_in_thread(daemon=True) for _ in range(10): await client.publish('my-channel', 'lalala') thread.stop()
async def test_pickled_object(): r = yaaredis.StrictRedis() obj = Exception('args') pickled_obj = pickle.dumps(obj) await r.set('pickled-obj', pickled_obj) cached_obj = await r.get('pickled-obj') assert isinstance(cached_obj, bytes) assert obj.args == pickle.loads(cached_obj).args
async def test_yaaredis(n): start = time.time() client = yaaredis.StrictRedis(host=HOST) res = None for _ in range(n): res = await client.keys('*') print(time.time() - start) return res
async def example(): client = yaaredis.StrictRedis() await client.flushall() cache = client.cache('example_cache', identity_generator_class=CustomIdentityGenerator) data = {1: 1} await cache.set('example_key', expensive_work(data), data) res = await cache.get('example_key', data) assert res == expensive_work(data)
async def get_version(**kwargs): params = {'host': 'localhost', 'port': 6379, 'db': 0} params.update(kwargs) key = '{}:{}'.format(params['host'], params['port']) if key not in _REDIS_VERSIONS: client = yaaredis.StrictRedis(**params) _REDIS_VERSIONS[key] = (await client.info())['redis_version'] client.connection_pool.disconnect() return _REDIS_VERSIONS[key]
async def test_busy_loading_disconnects_socket(event_loop): """ If Redis raises a LOADING error, the connection should be disconnected and a BusyLoadingError raised """ client = yaaredis.StrictRedis(loop=event_loop) with pytest.raises(BusyLoadingError): await client.execute_command('DEBUG', 'ERROR', 'LOADING fake message') pool = client.connection_pool assert len(pool._available_connections) == 0
async def _stream(res): redis = yaaredis.StrictRedis() pub = redis.pubsub() await pub.subscribe('test') end_time = app.loop.time() + 30 while app.loop.time() < end_time: await redis.publish('test', 111) message = None while not message: message = await pub.get_message() res.write(message) await asyncio.sleep(0.1)
async def run(): args = parse_args() r = yaaredis.StrictRedis() await r.flushall() await set_str(conn=r, num=args.n, pipeline_size=args.P, data_size=args.s) await set_int(conn=r, num=args.n, pipeline_size=args.P, data_size=args.s) await get_str(conn=r, num=args.n, pipeline_size=args.P) await get_int(conn=r, num=args.n, pipeline_size=args.P) await incr(conn=r, num=args.n, pipeline_size=args.P) await lpush(conn=r, num=args.n, pipeline_size=args.P, data_size=args.s) await lrange_300(conn=r, num=args.n, pipeline_size=args.P) await lpop(conn=r, num=args.n, pipeline_size=args.P) await hmset(conn=r, num=args.n, pipeline_size=args.P, data_size=args.s)
async def test_busy_loading_from_pipeline_immediate_command(event_loop): """ BusyLoadingErrors should raise from Pipelines that execute a command immediately, like WATCH does. """ client = yaaredis.StrictRedis(loop=event_loop) pipe = await client.pipeline() with pytest.raises(BusyLoadingError): await pipe.immediate_execute_command('DEBUG', 'ERROR', 'LOADING fake message') pool = client.connection_pool assert not pipe.connection assert len(pool._available_connections) == 0
async def test_on_connect_error(event_loop): """ An error in Connection.on_connect should disconnect from the server see for details: https://github.com/andymccurdy/redis-py/issues/368 """ # this assumes the Redis server being tested against doesn't have # 9999 databases ;) bad_connection = yaaredis.StrictRedis(db=9999, loop=event_loop) # an error should be raised on connect with pytest.raises(RedisError): await bad_connection.info() pool = bad_connection.connection_pool assert len(pool._available_connections) == 0
async def test_busy_loading_from_pipeline(event_loop): """ BusyLoadingErrors should be raised from a pipeline execution regardless of the raise_on_error flag. """ client = yaaredis.StrictRedis(loop=event_loop) pipe = await client.pipeline() await pipe.execute_command('DEBUG', 'ERROR', 'LOADING fake message') with pytest.raises(RedisError): await pipe.execute() pool = client.connection_pool assert not pipe.connection assert len(pool._available_connections) == 1 assert pool._available_connections[0]._writer assert pool._available_connections[0]._reader
async def test_connection_idle_check(): rs = yaaredis.StrictRedis(host='127.0.0.1', port=6379, db=0, max_idle_time=0.2, idle_check_interval=0.1) await rs.info() assert len(rs.connection_pool._available_connections) == 1 assert len(rs.connection_pool._in_use_connections) == 0 conn = rs.connection_pool._available_connections[0] last_active_at = conn.last_active_at await asyncio.sleep(0.3) assert len(rs.connection_pool._available_connections) == 0 assert len(rs.connection_pool._in_use_connections) == 0 assert last_active_at == conn.last_active_at assert conn._writer is None and conn._reader is None
def cached(cache): def decorator(func): @functools.wraps(func) async def _inner(*args, **kwargs): key = func.__name__ res = await cache.get(key, (args, kwargs)) if res: print(f'using cache: {res}') else: print('cache miss') res = func(*args, **kwargs) await cache.set(key, res, (args, kwargs)) return res return _inner return decorator CACHE = yaaredis.StrictRedis().cache('example_cache') @cached(cache=CACHE) def job(*args, **kwargs): return f'example_results for job({args}, {kwargs})' if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(job(111))
def r(): return yaaredis.StrictRedis(decode_responses=True)
def r(event_loop): return yaaredis.StrictRedis(loop=event_loop)
async def test_channel_subscribe(self, r): r = yaaredis.StrictRedis(host='localhost', port=6390) p = r.pubsub() with pytest.raises(ConnectionError): await p.subscribe('foo')