Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|> if len(res.keys()) != 1: raise RedisClusterException("More then 1 result from command") return list(res.values())[0] def blocked_command(self, command): """ Raises a `RedisClusterException` mentioning the command is blocked. """ raise RedisClusterExcep...
except ClusterDownError:
Based on the snippet: <|code_start|># ++++++++++ result callbacks (cluster)++++++++++++++ def merge_result(res): """ Merges all items in `res` into a list. This command is used when sending a command to multiple nodes and they result from each node should be merged into a single list. """ if no...
raise RedisClusterException("More then 1 result from command")
Based on the snippet: <|code_start|> async def sentinel_master(self, service_name): """Returns a dictionary containing the specified masters state.""" return await self.execute_command('SENTINEL MASTER', service_name) async def sentinel_masters(self): """Returns a list of dictionaries co...
NODES_FLAGS = dict_merge(
Here is a snippet: <|code_start|> def pairs_to_dict_typed(response, type_info): it = iter(response) result = {} for key, value in zip(it, it): if key in type_info: try: value = type_info[key](value) except: # if for some reason the value can't...
return parse_sentinel_state(map(nativestr, response))
Next line prediction: <|code_start|> """Returns a dictionary containing the specified masters state.""" return await self.execute_command('SENTINEL MASTER', service_name) async def sentinel_masters(self): """Returns a list of dictionaries containing each master's state.""" return awa...
list_keys_to_dict(
Continue the code snippet: <|code_start|> async def sentinel_masters(self): """Returns a list of dictionaries containing each master's state.""" return await self.execute_command('SENTINEL MASTERS') async def sentinel_monitor(self, name, ip, port, quorum): """Adds a new master to Sentine...
'SENTINEL SLAVES'], NodeFlag.BLOCKED
Here is a snippet: <|code_start|> ('is_master_down', 'master_down')): result[name] = flag in flags return result def parse_sentinel_master(response): return parse_sentinel_state(map(nativestr, response)) def parse_sentinel_masters(response): result = {} for item in resp...
'SENTINEL MONITOR': bool_ok,
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- async def example(conn): # connecting process will be done automatically when commands executed # you may not need to use that directly # directly use it if you want to reconnect a connection ...
conn = Connection(host='127.0.0.1', port=6379, db=0)
Based on the snippet: <|code_start|>""" `client reply off | on | skip` is hard to be supported by aredis gracefully because of the client pool usage. The client is supposed to read response from server and release connection after the command being sent. But the connection is needed to be always reused if you need to t...
conn = Connection(host='127.0.0.1', port=6379)
Next line prediction: <|code_start|> 3) 1) "10.0.0.1" 2) (integer) 10000 3) "3588b4cf9fc72d57bb262a024747797ead0cf7ea" 4) 1) "10.0.0.4" 2) (integer) 10000 3) "a72c02c7d85f4ec3145ab2c411eefc0812aa96b0" 2) 1) (integer) 10923 2) (integer) 16383 3) 1) "...
parse_cluster_slots(extended_mock_response)
Using the snippet: <|code_start|> 'node_id': b'3588b4cf9fc72d57bb262a024747797ead0cf7ea', 'port': 7002, 'server_type': 'master'}, {'host': b'172.17.0.2', 'node_id': b'a72c02c7d85f4ec3145ab2c411eefc0812aa96b0', 'port': 7005, 'server...
with pytest.raises(RedisClusterException) as ex:
Here is a snippet: <|code_start|> blocked_command(None, "SET") assert str(ex.value) == "Command: SET is blocked in redis cluster mode" def test_merge_result(): assert merge_result({"a": [1, 2, 3], "b": [4, 5, 6]}) == [1, 2, 3, 4, 5, 6] assert merge_result({"a": [1, 2, 3], "b": [1, 2, 3]}) == [1, 2,...
raise ClusterDownError("CLUSTERDOWN")
Continue the code snippet: <|code_start|> {'host': b'172.17.0.2', 'node_id': b'5c15b69186017ddc25ebfac81e74694fc0c1a160', 'port': 7003, 'server_type': 'slave'}], (5461, 10922): [ {'host': b'172.17.0.2', 'node_id': b'069cda388c7c41c62abe8...
assert list_keys_to_dict(["FOO", "BAR"], mock_true) == {"FOO": mock_true, "BAR": mock_true}
Given the code snippet: <|code_start|> 4) 1) "10.0.0.4" 2) (integer) 10000 3) "a72c02c7d85f4ec3145ab2c411eefc0812aa96b0" 2) 1) (integer) 10923 2) (integer) 16383 3) 1) "10.0.0.2" 2) (integer) 10000 3) "ffd36d8d7cb10d813f81f9662a835f6beea72677" 4) 1)...
[0, 5460, [b('172.17.0.2'), 7000, b('ffd36d8d7cb10d813f81f9662a835f6beea72677')], [b('172.17.0.2'), 7003, b('5c15b69186017ddc25ebfac81e74694fc0c1a160')]],
Using the snippet: <|code_start|> 'port': 7001, 'server_type': 'master'}, {'host': b'172.17.0.2', 'node_id': b'dc152a08b4cf1f2a0baf775fb86ad0938cb907dc', 'port': 7004, 'server_type': 'slave'}], (10923, 16383): [ {'host': b'1...
assert dict_merge(a, b, c) == {"a": 1, "b": 2, "c": 3}
Based on the snippet: <|code_start|> 'port': 7002, 'server_type': 'master'}, {'host': b'172.17.0.2', 'node_id': b'a72c02c7d85f4ec3145ab2c411eefc0812aa96b0', 'port': 7005, 'server_type': 'slave'}] } assert parse_cluster_slots(extended_m...
blocked_command(None, "SET")
Next line prediction: <|code_start|> 'server_type': 'slave'}] } assert parse_cluster_slots(extended_mock_binary_response) == extended_mock_parsed def test_list_keys_to_dict(): def mock_true(): return True assert list_keys_to_dict(["FOO", "BAR"], mock_true) == {"FOO": mock_true, "B...
assert merge_result({"a": [1, 2, 3], "b": [4, 5, 6]}) == [1, 2, 3, 4, 5, 6]
Given the following code snippet before the placeholder: <|code_start|> def test_dict_merge(): a = {"a": 1} b = {"b": 2} c = {"c": 3} assert dict_merge(a, b, c) == {"a": 1, "b": 2, "c": 3} def test_dict_merge_empty_list(): assert dict_merge([]) == {} def test_blocked_command(): with pytest....
assert first_key({"foo": 1}) == 1
Here is a snippet: <|code_start|>def test_blocked_command(): with pytest.raises(RedisClusterException) as ex: blocked_command(None, "SET") assert str(ex.value) == "Command: SET is blocked in redis cluster mode" def test_merge_result(): assert merge_result({"a": [1, 2, 3], "b": [4, 5, 6]}) == [1, 2...
@clusterdown_wrapper
Given the code snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class TestCache: app = 'test_cache' key = 'test_key' data = {str(i): i for i in range(3)} def expensive_work(self, data): return data @pytest.mark.asyncio(forbid_global_loop=True) async def test_set(se...
cache = Cache(r, self.app)
Predict the next line after this snippet: <|code_start|> assert ttl > 0 await asyncio.sleep(1.1, loop=event_loop) ttl = await cache.ttl(self.key, self.data) assert ttl < 0 @pytest.mark.asyncio(forbid_global_loop=True) async def test_exists(self, r, event_loop): await r.fl...
cache = HerdCache(r, self.app, default_herd_timeout=1,
Predict the next line for this snippet: <|code_start|> class HyperLogCommandMixin: RESPONSE_CALLBACKS = dict_merge( string_keys_to_dict('PFADD PFCOUNT', int), { <|code_end|> with the help of current file imports: import string import random from aredis.utils import (string_keys_to_dict, ...
'PFMERGE': bool_ok,
Continue the code snippet: <|code_start|> def __init__(self, startup_nodes=None, reinitialize_steps=None, skip_full_coverage_check=False, nodemanager_follow_cluster=False, **connection_kwargs): """ :skip_full_coverage_check: Skips the check of cluster-req...
value = b(str(value))
Using the snippet: <|code_start|> self.connection_kwargs = connection_kwargs self.nodes = {} self.slots = {} self.startup_nodes = [] if startup_nodes is None else startup_nodes self.orig_startup_nodes = self.startup_nodes[:] self.reinitialize_counter = 0 self.reini...
return hash_slot(key)
Based on the snippet: <|code_start|> connection_kwargs = {k: v for k, v in self.connection_kwargs.items() if k in allowed_keys} return StrictRedis(host=host, port=port, decode_responses=True, **connection_kwargs) async def initialize(self): """ Initializes the slots cache by asking a...
except ConnectionError:
Predict the next line for this snippet: <|code_start|> class NodeManager: """ TODO: document """ RedisClusterHashSlots = 16384 def __init__(self, startup_nodes=None, reinitialize_steps=None, skip_full_coverage_check=False, nodemanager_follow_cluster=False, **connec...
raise RedisClusterException("No startup nodes provided")
Based on the snippet: <|code_start|> class GetRedisKeyHandler(RequestHandler): def __init__(self, application, request, **kwargs): super(GetRedisKeyHandler, self).__init__(application, request, **kwargs) <|code_end|> , predict the immediate next line with the help of imports: import asyncio from aredis i...
self.redis_client = StrictRedis()
Continue the code snippet: <|code_start|># assert wait_for_message(p) is None # assert self.message == self.make_message('message', self.channel, # new_data) # # def test_pattern_message_handler(self, r): # p = r.pubsub(ignore_subscribe_messag...
with pytest.raises(ConnectionError):
Next line prediction: <|code_start|># # # test that we reconnected to the correct pattern # p.connection.disconnect() # assert wait_for_message(p) is None # should reconnect # new_data = self.data + 'new data' # r.publish(self.channel, new_data) # assert wait_for_message...
assert channels == [b('bar'), b('baz'), b('foo'), b('quux')]
Using the snippet: <|code_start|># p.psubscribe(**{self.pattern: self.message_handler}) # r.publish(self.channel, self.data) # assert wait_for_message(p) is None # assert self.message == self.make_message('pmessage', self.channel, # self.d...
@skip_if_server_version_lt('2.8.0')
Predict the next line after this snippet: <|code_start|> 'port': 6379, 'db': 3, 'password': None, } def test_extra_typed_querystring_options(self): pool = aredis.ConnectionPool.from_url( 'redis://localhost/2?stream_timeout=20&connect_timeout=10' ...
assert expected is to_bool(value)
Continue the code snippet: <|code_start|> self.awaiting_response = False class TestConnectionPool: def get_pool(self, connection_kwargs=None, max_connections=None, connection_class=DummyConnection): connection_kwargs = connection_kwargs or {} pool = aredis.ConnectionPool( ...
with pytest.raises(ConnectionError):
Predict the next line for this snippet: <|code_start|> pool = aredis.ConnectionPool.from_url( 'rediss://?ssl_cert_reqs=none&ssl_keyfile=test') assert e.message == 'certfile should be a valid filesystem path' assert pool.get_connection().ssl_context.verify_mode == ssl.C...
with pytest.raises(RedisError):
Using the snippet: <|code_start|> 'rediss://?ssl_cert_reqs=required&ssl_keyfile=test') assert e.message == 'certfile should be a valid filesystem path' assert pool.get_connection().ssl_context.verify_mode == ssl.CERT_REQUIRED class TestConnection: @pytest.mark.asyncio(forbi...
with pytest.raises(BusyLoadingError):
Predict the next line for this snippet: <|code_start|> 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 le...
with pytest.raises(ReadOnlyError):
Given snippet: <|code_start|> with pytest.raises(TypeError) as e: pool = aredis.ConnectionPool.from_url( 'rediss://?ssl_cert_reqs=optional&ssl_keyfile=test') assert e.message == 'certfile should be a valid filesystem path' assert pool.get_connection().ssl_conte...
@skip_if_server_version_lt('2.8.8')
Continue the code snippet: <|code_start|> def parse_cluster_slots(response): res = dict() for slot_info in response: min_slot, max_slot = slot_info[:2] nodes = slot_info[2:] parse_node = lambda node: { 'host': node[0], 'port': node[1], 'node_id': node[...
'CLUSTER ADDSLOTS': bool_ok,
Based on the snippet: <|code_start|> if len(parts) >= 9: slots, migrations = parse_slots(parts[8]) node['slots'], node['migrations'] = tuple(slots), migrations nodes.append(node) return nodes def parse_cluster_slots(response): res = dict() for slot_info in respons...
'CLUSTER INFO': NodeFlag.ALL_NODES,
Predict the next line after this snippet: <|code_start|> node['slots'], node['migrations'] = tuple(slots), migrations nodes.append(node) return nodes def parse_cluster_slots(response): res = dict() for slot_info in response: min_slot, max_slot = slot_info[:2] nodes = s...
list_keys_to_dict(
Given snippet: <|code_start|> } if len(parts) >= 9: slots, migrations = parse_slots(parts[8]) node['slots'], node['migrations'] = tuple(slots), migrations nodes.append(node) return nodes def parse_cluster_slots(response): res = dict() for slot_info in resp...
NODES_FLAGS = dict_merge({
Based on the snippet: <|code_start|> return res async def cluster_save_config(self): """ Forces the node to save cluster state on disk Sends to all nodes in the cluster """ return await self.execute_command('CLUSTER SAVECONFIG') async def cluster_set_config_epoc...
raise RedisError('Invalid slot state: {0}'.format(state))
Continue the code snippet: <|code_start|> return await self.execute_command('CLUSTER COUNT-FAILURE-REPORTS', node_id=node_id) async def cluster_countkeysinslot(self, slot_id): """ Return the number of local keys in the specified hash slot Send to node based on specefied slot_id ...
raise ClusterError('Wrong option provided')
Given the code snippet: <|code_start|> """ Appends the specified stream entry to the stream at the specified key. If the key does not exist, as a side effect of running this command the key is created with a stream value. Available since 5.0.0. Time complexity: O(log(N)) w...
raise RedisError("XADD maxlen must be a positive integer")
Using the snippet: <|code_start|> kv_pairs = r[1] kv_dict = dict() while kv_pairs and len(kv_pairs) > 1: kv_dict[kv_pairs.pop()] = kv_pairs.pop() result.append((r[0], kv_dict)) return result def multi_stream_list(response): result = dict() if ...
RESPONSE_CALLBACKS = dict_merge(
Given the code snippet: <|code_start|> def stream_list(response): result = [] if response: for r in response: kv_pairs = r[1] kv_dict = dict() while kv_pairs and len(kv_pairs) > 1: kv_dict[kv_pairs.pop()] = kv_pairs.pop() result.append((r[...
return [pairs_to_dict(row) for row in response]
Next line prediction: <|code_start|> kv_dict = dict() while kv_pairs and len(kv_pairs) > 1: kv_dict[kv_pairs.pop()] = kv_pairs.pop() result.append((r[0], kv_dict)) return result def multi_stream_list(response): result = dict() if response: for r i...
string_keys_to_dict('XREVRANGE XRANGE', stream_list),
Next line prediction: <|code_start|> def multi_stream_list(response): result = dict() if response: for r in response: result[r[0]] = stream_list(r[1]) return result def list_of_pairs_to_dict(response): return [pairs_to_dict(row) for row in response] def parse_xinfo_stream(respons...
'XGROUP SETID': bool_ok,
Predict the next line after this snippet: <|code_start|> For more discussion please see: https://github.com/NoneGG/aredis/issues/55 My solution is to take advantage of `READONLY` mode of slaves to ensure the lock key is synced from master to N/2 + 1 of its slaves to avoid the fail-over problem. Sinc...
conn = ClusterConnection(host=node['host'], port=node['port'], **conn_kwargs)
Predict the next line for this snippet: <|code_start|> time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds. thread-1 sets the token to "abc" time: 1, thread-2 blocks trying to acquire `my-lock` using the Lock instance. time: 5, t...
raise LockError("'sleep' must be less than 'timeout'")
Based on the snippet: <|code_start|> async def extend(self, additional_time): """ Adds more time to an already acquired lock. ``additional_time`` can be specified as an integer or a float, both representing the number of seconds to add. """ if self.local.get() is Non...
except WatchError:
Based on the snippet: <|code_start|> self.timeout = timeout self.sleep = sleep self.blocking = blocking self.blocking_timeout = blocking_timeout self.thread_local = bool(thread_local) self.local = contextvars.ContextVar('token', default=None) if self.thread_local else dumm...
token = b(uuid.uuid1().hex)
Predict the next line for this snippet: <|code_start|> another thread. Consider the following timeline: time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds. thread-1 sets the token to "abc" time: 1, thread-2 blocks trying to acquire `my-lock` using the ...
self.local = contextvars.ContextVar('token', default=None) if self.thread_local else dummy()
Using the snippet: <|code_start|>""" msgpack_hello_script_broken = """ local message = cmsgpack.unpack(ARGV[1]) local names = message['name'] return "hello " .. name """ class TestScripting: @pytest.mark.asyncio(forbid_global_loop=True) async def test_eval(self, r): await r.flushdb() await r....
with pytest.raises(NoScriptError):
Based on the snippet: <|code_start|> await r.script_flush() pipe = await r.pipeline() await pipe.set('a', 2) await pipe.get('a') await multiply.execute(keys=['a'], args=[3], client=pipe) assert await r.script_exists(multiply.sha) == [False] # [SET worked, GET 'a', ...
with pytest.raises(ResponseError) as excinfo:
Next line prediction: <|code_start|> @pytest.mark.asyncio(forbid_global_loop=True) async def test_script_object(self, r): await r.script_flush() await r.set('a', 2) multiply = r.register_script(multiply_script) precalculated_sha = multiply.sha assert precalculated_sha ...
assert await pipe.execute() == [True, b('2'), 6]
Predict the next line for this snippet: <|code_start|> 'ZADD ZCARD ZLEXCOUNT ' 'ZREM ZREMRANGEBYLEX ' 'ZREMRANGEBYRANK ' 'ZREMRANGEBYSCORE', int ), string_keys_to_dict('ZSCORE ZINCRBY', float_or_none), string_keys_to_dict( 'ZRANGE ZRANGE...
raise RedisError("ZADD requires an equal number of "
Continue the code snippet: <|code_start|> """ return await self._zaggregate('ZINTERSTORE', dest, keys, aggregate) async def zlexcount(self, name, min, max): """ Returns the number of items in the sorted set ``name`` between the lexicographical range ``min`` and ``max``. ...
pieces.append(b('WITHSCORES'))
Here is a snippet: <|code_start|> 'ZREMRANGEBYSCORE', int ), string_keys_to_dict('ZSCORE ZINCRBY', float_or_none), string_keys_to_dict( 'ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCORE', zset_score_pairs ), string_keys_to_dict('ZRANK ZREVRANK', ...
for pair in iteritems(kwargs):
Using the snippet: <|code_start|> pieces.extend(weights) if aggregate: pieces.append(b('AGGREGATE')) pieces.append(aggregate) return await self.execute_command(*pieces) async def zscan(self, name, cursor=0, match=None, count=None, score_cast_fu...
'ZSCAN': first_key
Continue the code snippet: <|code_start|> if withscores: pieces.append(b('WITHSCORES')) options = { 'withscores': withscores, 'score_cast_func': score_cast_func } return await self.execute_command(*pieces, **options) async def zrevrank(self, name, ...
keys, weights = iterkeys(keys), itervalues(keys)
Predict the next line after this snippet: <|code_start|> if withscores: pieces.append(b('WITHSCORES')) options = { 'withscores': withscores, 'score_cast_func': score_cast_func } return await self.execute_command(*pieces, **options) async def zrevra...
keys, weights = iterkeys(keys), itervalues(keys)
Based on the snippet: <|code_start|>VALID_ZADD_OPTIONS = {'NX', 'XX', 'CH', 'INCR'} def float_or_none(response): if response is None: return None return float(response) def zset_score_pairs(response, **options): """ If ``withscores`` is specified in the options, return the response as a ...
RESPONSE_CALLBACKS = dict_merge(
Using the snippet: <|code_start|> def float_or_none(response): if response is None: return None return float(response) def zset_score_pairs(response, **options): """ If ``withscores`` is specified in the options, return the response as a list of (value, score) pairs """ if not res...
string_keys_to_dict(
Next line prediction: <|code_start|> a list of (value, score) pairs """ if not response or not options['withscores']: return response score_cast_func = options.get('score_cast_func', float) it = iter(response) return list(zip(it, map(score_cast_func, it))) def parse_zscan(response, **op...
string_keys_to_dict('ZRANK ZREVRANK', int_or_none),
Next line prediction: <|code_start|> @pytest.mark.asyncio() async def test_eval_same_slot(self, r): await r.set('A{foo}', 2) await r.set('B{foo}', 4) # 2 * 4 == 8 script = """ local value = redis.call('GET', KEYS[1]) local value2 = redis.call('GET', KEYS[2]) ...
with pytest.raises(RedisClusterException):
Next line prediction: <|code_start|> async def test_eval_crossslot(self, r): """ This test assumes that {foo} and {bar} will not go to the same server when used. In 3 masters + 3 slaves config this should pass. """ await r.set('A{foo}', 2) await r.set('B{bar}', 4) ...
with pytest.raises(NoScriptError):
Given snippet: <|code_start|> await r.script_flush() pipe = await r.pipeline() await pipe.set('a', 2) await pipe.get('a') assert multiply.sha multiply(keys=['a'], args=[3], client=pipe) assert await r.script_exists(multiply.sha) == [False] # [SET worked, GE...
with pytest.raises(ResponseError) as excinfo:
Next line prediction: <|code_start|> assert await r.script_exists(sha) == [False] await r.script_load(multiply_script) assert await r.script_exists(sha) == [True] @pytest.mark.asyncio() async def test_script_object(self, r): await r.set('a', 2) multiply = r.register_scrip...
assert await pipe.execute() == [True, b('2'), 6]
Next line prediction: <|code_start|> return await self.execute_command('SRANDMEMBER', name, *args) async def srem(self, name, *values): """Removes ``values`` from set ``name``""" return await self.execute_command('SREM', name, *values) async def sunion(self, keys, *args): """Ret...
pieces.extend([b('MATCH'), match])
Given the code snippet: <|code_start|> def parse_sscan(response, **options): cursor, r = response return int(cursor), r class SetsCommandMixin: <|code_end|> , generate the next line using the imports in this file: from aredis.utils import (b, dict_merge, list_or_args, ...
RESPONSE_CALLBACKS = dict_merge(
Given snippet: <|code_start|>class SetsCommandMixin: RESPONSE_CALLBACKS = dict_merge( string_keys_to_dict( 'SADD SCARD SDIFFSTORE ' 'SETRANGE SINTERSTORE ' 'SREM SUNIONSTORE', int ), string_keys_to_dict( 'SISMEMBER SMOVE', bool ), ...
args = list_or_args(keys, args)
Predict the next line after this snippet: <|code_start|> return await self.execute_command('SUNION', *args) async def sunionstore(self, dest, keys, *args): """ Stores the union of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. ...
'SSCAN': first_key
Next line prediction: <|code_start|> def parse_sscan(response, **options): cursor, r = response return int(cursor), r class SetsCommandMixin: RESPONSE_CALLBACKS = dict_merge( <|code_end|> . Use current file imports: (from aredis.utils import (b, dict_merge, list_or_args, ...
string_keys_to_dict(
Based on the snippet: <|code_start|> """ if self.decode_responses and isinstance(value, bytes): value = value.decode(self.encoding) elif not self.decode_responses and isinstance(value, str): value = value.encode(self.encoding) return value @property def su...
except CancelledError:
Given the code snippet: <|code_start|> if message_type == 'punsubscribe': subscribed_dict = self.patterns else: subscribed_dict = self.channels try: del subscribed_dict[message['channel']] except KeyError: pas...
raise PubSubError("Channel: '{}' has no handler registered"
Given snippet: <|code_start|> @property def subscribed(self): """Indicates if there are subscriptions to any channels or patterns""" return bool(self.channels or self.patterns) async def execute_command(self, *args, **kwargs): """Executes a publish/subscribe command""" # NOT...
except (ConnectionError, TimeoutError) as e:
Continue the code snippet: <|code_start|> @property def subscribed(self): """Indicates if there are subscriptions to any channels or patterns""" return bool(self.channels or self.patterns) async def execute_command(self, *args, **kwargs): """Executes a publish/subscribe command""" ...
except (ConnectionError, TimeoutError) as e:
Based on the snippet: <|code_start|> await connection.connect() # the ``on_connect`` callback should haven been called by the # connection to resubscribe us to any channels and patterns we were # previously listening to return await command(*args) async de...
args = list_or_args(args[0], args[1:])
Here is a snippet: <|code_start|> self.reset() def __del__(self): try: # if this object went out of scope prior to shutting down # subscriptions, close the connection manually before # returning it to the connection pool self.reset() except Exc...
for k, v in iteritems(self.channels):
Given the code snippet: <|code_start|> async def parse_response(self, block=True, timeout=0): """Parses the response from a publish/subscribe command""" connection = self.connection if connection is None: raise RuntimeError( 'pubsub connection not set: ' ...
ret_val = await self.execute_command('PSUBSCRIBE', *iterkeys(new_patterns))
Given snippet: <|code_start|> if args: args = list_or_args(args[0], args[1:]) return await self.execute_command('UNSUBSCRIBE', *args) async def listen(self): """ Listens for messages on channels this client has been subscribed to """ if self.subscribed: ...
message_type = nativestr(response[0])
Given snippet: <|code_start|>from __future__ import with_statement class TestPipeline: @pytest.mark.asyncio(forbid_global_loop=True) async def test_pipeline(self, r): await r.flushdb() async with await r.pipeline() as pipe: await pipe.set('a', 'a1') await pipe.get('a'...
b('a1'),
Here is a snippet: <|code_start|> assert await r.get('b') == b('b1') assert await r.get('c') == b('c1') @pytest.mark.asyncio(forbid_global_loop=True) async def test_pipeline_no_transaction_watch(self, r): await r.flushdb() await r.set('a', 0) async with await r.p...
with pytest.raises(WatchError):
Predict the next line for this snippet: <|code_start|> pipe.multi() await pipe.set('a', int(a) + 1) with pytest.raises(WatchError): await pipe.execute() assert await r.get('a') == b('bad') @pytest.mark.asyncio(forbid_global_loop=True) async def t...
assert isinstance(result[2], ResponseError)
Given snippet: <|code_start|> assert await r.config_set('dbfilename', rdbname) @pytest.mark.asyncio(forbid_global_loop=True) async def test_dbsize(self, r): await r.flushdb() await r.set('a', 'foo') await r.set('b', 'bar') assert await r.dbsize() == 2 @pytest.mar...
assert await r.object('encoding', 'a') in (b('raw'), b('embstr'))
Based on the snippet: <|code_start|> await r.flushdb() assert await r.incrbyfloat('a') == 1.0 assert await r.get('a') == b('1') assert await r.incrbyfloat('a', 1.1) == 2.1 assert float(await r.get('a')) == float(2.1) @pytest.mark.asyncio(forbid_global_loop=True) async def...
for k, v in iteritems(d):
Given snippet: <|code_start|> assert await r.hexists('a', '1') assert not await r.hexists('a', '4') @pytest.mark.asyncio(forbid_global_loop=True) async def test_hgetall(self, r): await r.flushdb() h = {b('a1'): b('1'), b('a2'): b('2'), b('a3'): b('3')} await r.hmset('a', ...
local_keys = list(iterkeys(h))
Predict the next line after this snippet: <|code_start|> await r.hmset('a', {'1': 1, '2': 2, '3': 3}) assert await r.hlen('a') == 3 @pytest.mark.asyncio(forbid_global_loop=True) async def test_hmget(self, r): await r.flushdb() assert await r.hmset('a', {'a': 1, 'b': 2, 'c': 3}) ...
local_vals = list(itervalues(h))
Given snippet: <|code_start|> async def test_22_info(self, r): """ Older Redis versions contained 'allocation_stats' in INFO that was the cause of a number of bugs when parsing. """ await r.flushdb() info = b"allocation_stats:6=1,7=1,8=7141,9=180,10=92,11=116,12=5330,"...
parsed = parse_info(info)
Continue the code snippet: <|code_start|> @pytest.mark.asyncio(forbid_global_loop=True) async def test_bitop_string_operands(self, r): await r.set('a', b('\x01\x02\xFF\xFF')) await r.set('b', b('\x01\x02\xFF')) await r.bitop('and', 'res1', 'a', 'b') await r.bitop('or', 'res2', 'a'...
with pytest.raises(RedisError):
Based on the snippet: <|code_start|>from __future__ import with_statement async def redis_server_time(client): seconds, milliseconds = await client.time() timestamp = float('%s.%s' % (seconds, milliseconds)) return datetime.datetime.fromtimestamp(timestamp) # RESPONSE CALLBACKS class TestResponseCallb...
with pytest.raises(ResponseError):
Using the snippet: <|code_start|> await r.rpush('a', '2', '3', '1') assert await r.sort('a', get='user:*') == [b('u1'), b('u2'), b('u3')] @pytest.mark.asyncio(forbid_global_loop=True) async def test_sort_get_multi(self, r): await r.flushdb() await r.set('user:1', 'u1') aw...
with pytest.raises(DataError):
Given the code snippet: <|code_start|> # RESPONSE CALLBACKS class TestResponseCallbacks: "Tests for the response callback system" @pytest.mark.asyncio(forbid_global_loop=True) async def test_response_callbacks(self, r): assert r.response_callbacks == aredis.StrictRedis.RESPONSE_CALLBACKS as...
@skip_if_server_version_lt('2.6.9')
Here is a snippet: <|code_start|> await r.flushdb() assert await r.rpush('a', '1') == 1 assert await r.rpush('a', '2') == 2 assert await r.rpush('a', '3', '4') == 4 assert await r.lrange('a', 0, -1) == [b('1'), b('2'), b('3'), b('4')] @pytest.mark.asyncio(forbid_global_loop=T...
@skip_python_vsersion_lt('3.6')
Here is a snippet: <|code_start|> try: except ImportError: class IdentityGenerator: """ Generator of identity for unique key, you may overwrite it to meet your customize requirements. """ TEMPLATE = '{app}:{key}:{content}' def __init__(self, app, encoding='utf-8'): self.app = app ...
content = b(str(content))
Using the snippet: <|code_start|> return content def decompress(self, content): content = self._trans_type(content) try: return zlib.decompress(content) except zlib.error as exc: raise CompressError('Content can not be decompressed.') class Serializer: "...
raise SerializeError('Content can not be serialized.')
Given the code snippet: <|code_start|> class Compressor: """ Uses zlib to compress and decompress Redis cache. You may implement your own Compressor implementing `compress` and `decompress` methods """ min_length = 15 preset = 6 def __init__(self, encoding='utf-8'): self.encoding =...
raise CompressError('Content can not be compressed.')
Given the following code snippet before the placeholder: <|code_start|> else: return await asyncio.wait_for(coroutine, timeout, loop=loop) except asyncio.TimeoutError as exc: raise TimeoutError(exc) class SocketBuffer: def __init__(self, stream_reader, read_size): self._stre...
raise ConnectionError('Socket closed on remote end')
Continue the code snippet: <|code_start|> try: HIREDIS_AVAILABLE = True except ImportError: HIREDIS_AVAILABLE = False SYM_STAR = b('*') SYM_DOLLAR = b('$') SYM_CRLF = b('\r\n') SYM_LF = b('\n') SYM_EMPTY = b('') async def exec_with_timeout(coroutine, timeout, *, loop=None): try: if LOOP_DEPREC...
except asyncio.TimeoutError as exc:
Given snippet: <|code_start|> # single value elif byte == '+': pass # int value elif byte == ':': response = int(response) # bulk response elif byte == '$': length = int(response) if length == -1: return None ...
raise RedisError("Hiredis is not installed")