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 RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
def clusterdown_wrapper(func):
"""
Wrapper for CLUSTERDOWN error handling.
If the cluster reports it is down it is assumed that:
- connection_pool was disconnected
- connection_pool was reseted
- refereh_table_asap set to True
It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
"""
@wraps(func)
async def inner(*args, **kwargs):
for _ in range(0, 3):
try:
return await func(*args, **kwargs)
<|code_end|>
. Write the next line using the current file imports:
import sys
from functools import wraps
from aredis.exceptions import (ClusterDownError, RedisClusterException)
from aredis.speedups import crc16, hash_slot
and context from other files:
# Path: aredis/exceptions.py
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class RedisClusterException(Exception):
# pass
, which may include functions, classes, or code. Output only the next line. | 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 not isinstance(res, dict):
raise ValueError('Value should be of dict type')
result = set([])
for _, v in res.items():
for value in v:
result.add(value)
return list(result)
def first_key(res):
"""
Returns the first result for the given command.
If more then 1 result is returned then a `RedisClusterException` is raised.
"""
if not isinstance(res, dict):
raise ValueError('Value should be of dict type')
if len(res.keys()) != 1:
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
from functools import wraps
from aredis.exceptions import (ClusterDownError, RedisClusterException)
from aredis.speedups import crc16, hash_slot
and context (classes, functions, sometimes code) from other files:
# Path: aredis/exceptions.py
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class RedisClusterException(Exception):
# pass
. Output only the next line. | 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 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 Sentinel to be monitored"""
return await self.execute_command('SENTINEL MONITOR', name, ip, port, quorum)
async def sentinel_remove(self, name):
"""Removes a master from Sentinel's monitoring"""
return await self.execute_command('SENTINEL REMOVE', name)
async def sentinel_sentinels(self, service_name):
"""Returns a list of sentinels for ``service_name``"""
return await self.execute_command('SENTINEL SENTINELS', service_name)
async def sentinel_set(self, name, option, value):
"""Sets Sentinel monitoring parameters for a given master"""
return await self.execute_command('SENTINEL SET', name, option, value)
async def sentinel_slaves(self, service_name):
"""Returns a list of slaves for ``service_name``"""
return await self.execute_command('SENTINEL SLAVES', service_name)
class ClusterSentinelCommands(SentinelCommandMixin):
<|code_end|>
, predict the immediate next line with the help of imports:
import warnings
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | 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 be coerced, just use
# the string value
pass
result[key] = value
return result
def parse_sentinel_state(item):
result = pairs_to_dict_typed(item, SENTINEL_STATE_TYPES)
flags = set(result['flags'].split(','))
for name, flag in (('is_master', 'master'), ('is_slave', 'slave'),
('is_sdown', 's_down'), ('is_odown', 'o_down'),
('is_sentinel', 'sentinel'),
('is_disconnected', 'disconnected'),
('is_master_down', 'master_down')):
result[name] = flag in flags
return result
def parse_sentinel_master(response):
<|code_end|>
. Write the next line using the current file imports:
import warnings
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok)
and context from other files:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
, which may include functions, classes, or code. Output only the next line. | 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 await self.execute_command('SENTINEL MASTERS')
async def sentinel_monitor(self, name, ip, port, quorum):
"""Adds a new master to Sentinel to be monitored"""
return await self.execute_command('SENTINEL MONITOR', name, ip, port, quorum)
async def sentinel_remove(self, name):
"""Removes a master from Sentinel's monitoring"""
return await self.execute_command('SENTINEL REMOVE', name)
async def sentinel_sentinels(self, service_name):
"""Returns a list of sentinels for ``service_name``"""
return await self.execute_command('SENTINEL SENTINELS', service_name)
async def sentinel_set(self, name, option, value):
"""Sets Sentinel monitoring parameters for a given master"""
return await self.execute_command('SENTINEL SET', name, option, value)
async def sentinel_slaves(self, service_name):
"""Returns a list of slaves for ``service_name``"""
return await self.execute_command('SENTINEL SLAVES', service_name)
class ClusterSentinelCommands(SentinelCommandMixin):
NODES_FLAGS = dict_merge(
<|code_end|>
. Use current file imports:
(import warnings
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | 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 Sentinel to be monitored"""
return await self.execute_command('SENTINEL MONITOR', name, ip, port, quorum)
async def sentinel_remove(self, name):
"""Removes a master from Sentinel's monitoring"""
return await self.execute_command('SENTINEL REMOVE', name)
async def sentinel_sentinels(self, service_name):
"""Returns a list of sentinels for ``service_name``"""
return await self.execute_command('SENTINEL SENTINELS', service_name)
async def sentinel_set(self, name, option, value):
"""Sets Sentinel monitoring parameters for a given master"""
return await self.execute_command('SENTINEL SET', name, option, value)
async def sentinel_slaves(self, service_name):
"""Returns a list of slaves for ``service_name``"""
return await self.execute_command('SENTINEL SLAVES', service_name)
class ClusterSentinelCommands(SentinelCommandMixin):
NODES_FLAGS = dict_merge(
list_keys_to_dict(
['SENTINEL GET-MASTER-ADDR-BY-NAME', 'SENTINEL MASTER', 'SENTINEL MASTERS',
'SENTINEL MONITOR', 'SENTINEL REMOVE', 'SENTINEL SENTINELS', 'SENTINEL SET',
<|code_end|>
. Use current file imports:
import warnings
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok)
and context (classes, functions, or code) from other files:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | '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 response:
state = parse_sentinel_state(map(nativestr, item))
result[state['name']] = state
return result
def parse_sentinel_slaves_and_sentinels(response):
return [parse_sentinel_state(map(nativestr, item)) for item in response]
def parse_sentinel_get_master(response):
return response and (response[0], int(response[1])) or None
class SentinelCommandMixin:
RESPONSE_CALLBACKS = {
'SENTINEL GET-MASTER-ADDR-BY-NAME': parse_sentinel_get_master,
'SENTINEL MASTER': parse_sentinel_master,
'SENTINEL MASTERS': parse_sentinel_masters,
<|code_end|>
. Write the next line using the current file imports:
import warnings
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok)
and context from other files:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
, which may include functions, classes, or code. Output only the next line. | '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 instance
await conn.connect()
assert not await conn.can_read()
await conn.send_command('keys', '*')
assert await conn.can_read()
print(await conn.read_response())
conn.disconnect()
await conn.send_command('set', 'foo', 1)
print(await conn.read_response())
if __name__ == '__main__':
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
from aredis import Connection
and context including class names, function names, and sometimes code from other files:
# Path: aredis/connection.py
# class Connection(BaseConnection):
# description = 'Connection<host={host},port={port},db={db}>'
#
# def __init__(self, host='127.0.0.1', port=6379, password=None,
# db=0, retry_on_timeout=False, stream_timeout=None, connect_timeout=None,
# ssl_context=None, parser_class=DefaultParser, reader_read_size=65535,
# encoding='utf-8', decode_responses=False, socket_keepalive=None,
# socket_keepalive_options=None, *, loop=None):
# super(Connection, self).__init__(retry_on_timeout, stream_timeout,
# parser_class, reader_read_size,
# encoding, decode_responses,
# loop=loop)
# self.host = host
# self.port = port
# self.password = password
# self.db = db
# self.ssl_context = ssl_context
# self._connect_timeout = connect_timeout
# self._description_args = {
# 'host': self.host,
# 'port': self.port,
# 'db': self.db
# }
# self.socket_keepalive = socket_keepalive
# self.socket_keepalive_options = socket_keepalive_options or {}
#
# async def _connect(self):
# reader, writer = await exec_with_timeout(
# asyncio.open_connection(host=self.host,
# port=self.port,
# ssl=self.ssl_context,
# loop=self.loop),
# self._connect_timeout,
# loop=self.loop
# )
# self._reader = reader
# self._writer = writer
# sock = writer.transport.get_extra_info('socket')
# if sock is not None:
# sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# try:
# # TCP_KEEPALIVE
# if self.socket_keepalive:
# sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
# for k, v in self.socket_keepalive_options.items():
# sock.setsockopt(socket.SOL_TCP, k, v)
# except (socket.error, TypeError):
# # `socket_keepalive_options` might contain invalid options
# # causing an error. Do not leave the connection open.
# writer.close()
# raise
# await self.on_connect()
. Output only the next line. | 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 turn on | off | skip the reply,
it should always be the connection by which you send `client reply` command to server you use to send the rest commands.
However, you can use the connection by your self like the example below~
"""
async def skip():
print('skip response example::')
<|code_end|>
, predict the immediate next line with the help of imports:
from aredis import Connection
import asyncio
and context (classes, functions, sometimes code) from other files:
# Path: aredis/connection.py
# class Connection(BaseConnection):
# description = 'Connection<host={host},port={port},db={db}>'
#
# def __init__(self, host='127.0.0.1', port=6379, password=None,
# db=0, retry_on_timeout=False, stream_timeout=None, connect_timeout=None,
# ssl_context=None, parser_class=DefaultParser, reader_read_size=65535,
# encoding='utf-8', decode_responses=False, socket_keepalive=None,
# socket_keepalive_options=None, *, loop=None):
# super(Connection, self).__init__(retry_on_timeout, stream_timeout,
# parser_class, reader_read_size,
# encoding, decode_responses,
# loop=loop)
# self.host = host
# self.port = port
# self.password = password
# self.db = db
# self.ssl_context = ssl_context
# self._connect_timeout = connect_timeout
# self._description_args = {
# 'host': self.host,
# 'port': self.port,
# 'db': self.db
# }
# self.socket_keepalive = socket_keepalive
# self.socket_keepalive_options = socket_keepalive_options or {}
#
# async def _connect(self):
# reader, writer = await exec_with_timeout(
# asyncio.open_connection(host=self.host,
# port=self.port,
# ssl=self.ssl_context,
# loop=self.loop),
# self._connect_timeout,
# loop=self.loop
# )
# self._reader = reader
# self._writer = writer
# sock = writer.transport.get_extra_info('socket')
# if sock is not None:
# sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# try:
# # TCP_KEEPALIVE
# if self.socket_keepalive:
# sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
# for k, v in self.socket_keepalive_options.items():
# sock.setsockopt(socket.SOL_TCP, k, v)
# except (socket.error, TypeError):
# # `socket_keepalive_options` might contain invalid options
# # causing an error. Do not leave the connection open.
# writer.close()
# raise
# await self.on_connect()
. Output only the next line. | 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) "10.0.0.2"
2) (integer) 10000
3) "ffd36d8d7cb10d813f81f9662a835f6beea72677"
4) 1) "10.0.0.5"
2) (integer) 10000
3) "5c15b69186017ddc25ebfac81e74694fc0c1a160"
3) 1) (integer) 0
2) (integer) 5460
3) 1) "10.0.0.3"
2) (integer) 10000
3) "069cda388c7c41c62abe892d9e0a2d55fbf5ffd5"
4) 1) "10.0.0.6"
2) (integer) 10000
3) "dc152a08b4cf1f2a0baf775fb86ad0938cb907dc"
"""
extended_mock_response = [
[0, 5460, ['172.17.0.2', 7000, 'ffd36d8d7cb10d813f81f9662a835f6beea72677'], ['172.17.0.2', 7003, '5c15b69186017ddc25ebfac81e74694fc0c1a160']],
[5461, 10922, ['172.17.0.2', 7001, '069cda388c7c41c62abe892d9e0a2d55fbf5ffd5'], ['172.17.0.2', 7004, 'dc152a08b4cf1f2a0baf775fb86ad0938cb907dc']],
[10923, 16383, ['172.17.0.2', 7002, '3588b4cf9fc72d57bb262a024747797ead0cf7ea'], ['172.17.0.2', 7005, 'a72c02c7d85f4ec3145ab2c411eefc0812aa96b0']]
]
<|code_end|>
. Use current file imports:
(from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
. Output only the next line. | 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_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, "BAR": mock_true}
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():
<|code_end|>
, determine the next line of code. You have imports:
from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest
and context (class names, function names, or code) available:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
. Output only the next line. | 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, 3]
def test_merge_result_value_error():
with pytest.raises(ValueError):
merge_result([])
def test_first_key():
assert first_key({"foo": 1}) == 1
with pytest.raises(RedisClusterException) as ex:
first_key({"foo": 1, "bar": 2})
assert str(ex.value).startswith("More then 1 result from command")
def test_first_key_value_error():
with pytest.raises(ValueError):
first_key(None)
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_clusterdown_wrapper():
@clusterdown_wrapper
def bad_func():
<|code_end|>
. Write the next line using the current file imports:
from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest
and context from other files:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
, which may include functions, classes, or code. Output only the next line. | 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'069cda388c7c41c62abe892d9e0a2d55fbf5ffd5',
'port': 7001,
'server_type': 'master'},
{'host': b'172.17.0.2',
'node_id': b'dc152a08b4cf1f2a0baf775fb86ad0938cb907dc',
'port': 7004,
'server_type': 'slave'}],
(10923, 16383): [
{'host': b'172.17.0.2',
'node_id': b'3588b4cf9fc72d57bb262a024747797ead0cf7ea',
'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_mock_binary_response) == extended_mock_parsed
def test_list_keys_to_dict():
def mock_true():
return True
<|code_end|>
. Use current file imports:
from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest
and context (classes, functions, or code) from other files:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
. Output only the next line. | 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) "10.0.0.5"
2) (integer) 10000
3) "5c15b69186017ddc25ebfac81e74694fc0c1a160"
3) 1) (integer) 0
2) (integer) 5460
3) 1) "10.0.0.3"
2) (integer) 10000
3) "069cda388c7c41c62abe892d9e0a2d55fbf5ffd5"
4) 1) "10.0.0.6"
2) (integer) 10000
3) "dc152a08b4cf1f2a0baf775fb86ad0938cb907dc"
"""
extended_mock_response = [
[0, 5460, ['172.17.0.2', 7000, 'ffd36d8d7cb10d813f81f9662a835f6beea72677'], ['172.17.0.2', 7003, '5c15b69186017ddc25ebfac81e74694fc0c1a160']],
[5461, 10922, ['172.17.0.2', 7001, '069cda388c7c41c62abe892d9e0a2d55fbf5ffd5'], ['172.17.0.2', 7004, 'dc152a08b4cf1f2a0baf775fb86ad0938cb907dc']],
[10923, 16383, ['172.17.0.2', 7002, '3588b4cf9fc72d57bb262a024747797ead0cf7ea'], ['172.17.0.2', 7005, 'a72c02c7d85f4ec3145ab2c411eefc0812aa96b0']]
]
parse_cluster_slots(extended_mock_response)
extended_mock_binary_response = [
<|code_end|>
, generate the next line using the imports in this file:
from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
. Output only the next line. | [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'172.17.0.2',
'node_id': b'3588b4cf9fc72d57bb262a024747797ead0cf7ea',
'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_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, "BAR": mock_true}
def test_dict_merge():
a = {"a": 1}
b = {"b": 2}
c = {"c": 3}
<|code_end|>
, determine the next line of code. You have imports:
from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest
and context (class names, function names, or code) available:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
. Output only the next line. | 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_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, "BAR": mock_true}
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.raises(RedisClusterException) as ex:
<|code_end|>
, predict the immediate next line with the help of imports:
from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
. Output only the next line. | 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, "BAR": mock_true}
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.raises(RedisClusterException) as ex:
blocked_command(None, "SET")
assert str(ex.value) == "Command: SET is blocked in redis cluster mode"
def test_merge_result():
<|code_end|>
. Use current file imports:
(from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
. Output only the next line. | 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.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, 3, 4, 5, 6]
assert merge_result({"a": [1, 2, 3], "b": [1, 2, 3]}) == [1, 2, 3]
def test_merge_result_value_error():
with pytest.raises(ValueError):
merge_result([])
def test_first_key():
<|code_end|>
, predict the next line using imports from the current file:
from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
. Output only the next line. | 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, 3, 4, 5, 6]
assert merge_result({"a": [1, 2, 3], "b": [1, 2, 3]}) == [1, 2, 3]
def test_merge_result_value_error():
with pytest.raises(ValueError):
merge_result([])
def test_first_key():
assert first_key({"foo": 1}) == 1
with pytest.raises(RedisClusterException) as ex:
first_key({"foo": 1, "bar": 2})
assert str(ex.value).startswith("More then 1 result from command")
def test_first_key_value_error():
with pytest.raises(ValueError):
first_key(None)
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_clusterdown_wrapper():
<|code_end|>
. Write the next line using the current file imports:
from aredis.commands.cluster import parse_cluster_slots
from aredis.exceptions import (
RedisClusterException, ClusterDownError
)
from aredis.utils import (
list_keys_to_dict,
b, dict_merge,
blocked_command,
merge_result,
first_key,
clusterdown_wrapper,
)
import pytest
and context from other files:
# Path: aredis/commands/cluster.py
# 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[2] if len(node) > 2 else '',
# 'server_type': 'slave'
# }
# res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
# res[(min_slot, max_slot)][0]['server_type'] = 'master'
# return res
#
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# Path: aredis/utils.py
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def blocked_command(self, command):
# """
# Raises a `RedisClusterException` mentioning the command is blocked.
# """
# raise RedisClusterException("Command: {0} is blocked in redis cluster mode".format(command))
#
# 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 not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def clusterdown_wrapper(func):
# """
# Wrapper for CLUSTERDOWN error handling.
#
# If the cluster reports it is down it is assumed that:
# - connection_pool was disconnected
# - connection_pool was reseted
# - refereh_table_asap set to True
#
# It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
# """
#
# @wraps(func)
# async def inner(*args, **kwargs):
# for _ in range(0, 3):
# try:
# return await func(*args, **kwargs)
# except ClusterDownError:
# # Try again with the new cluster setup. All other errors
# # should be raised.
# pass
#
# # If it fails 3 times then raise exception back to caller
# raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster")
#
# return inner
, which may include functions, classes, or code. Output only the next line. | @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(self, r):
await r.flushdb()
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import pytest
import time
from aredis.cache import Cache, HerdCache
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/cache.py
# class Cache(BasicCache):
# """Provides basic caching"""
#
# async def get(self, key, param=None):
# identity = self._gen_identity(key, param)
# res = await self.client.get(identity)
# if res:
# res = self._unpack(res)
# return res
#
# async def set(self, key, value, param=None, expire_time=None):
# identity = self._gen_identity(key, param)
# value = self._pack(value)
# return await self.client.set(identity, value, ex=expire_time)
#
# async def set_many(self, data, param=None, expire_time=None):
# async with await self.client.pipeline() as pipeline:
# for key, value in data.items():
# identity = self._gen_identity(key, param)
# value = self._pack(value)
# await pipeline.set(identity, value, expire_time)
# return await pipeline.execute()
#
# class HerdCache(BasicCache):
# """
# Cache that handles thundering herd problem
# (https://en.wikipedia.org/wiki/Thundering_herd_problem)
# by cacheing expiration time in set instead of directly using expire
# operation of redis.
# This kind of cache is suitable for low consistency scene where update
# operations are expensive.
# """
#
# def __init__(self, client, app='', identity_generator_class=IdentityGenerator,
# compressor_class=Compressor, serializer_class=Serializer,
# default_herd_timeout=1, extend_herd_timeout=1, encoding='utf-8'):
# self.default_herd_timeout = default_herd_timeout
# self.extend_herd_timeout = extend_herd_timeout
# super(HerdCache, self).__init__(client, app, identity_generator_class,
# compressor_class, serializer_class,
# encoding)
#
# async def set(self, key, value, param=None, expire_time=None, herd_timeout=None):
# """
# Uses key and param to generate identity and pack the content,
# expire the key within real_timeout if expire_time is given.
# real_timeout is equal to the sum of expire_time and herd_time.
# The content is cached with expire_time.
# """
# identity = self._gen_identity(key, param)
# expected_expired_ts = int(time.time())
# if expire_time:
# expected_expired_ts += expire_time
# expected_expired_ts += herd_timeout or self.default_herd_timeout
# value = self._pack([value, expected_expired_ts])
# return await self.client.set(identity, value, ex=expire_time)
#
# async def set_many(self, data, param=None, expire_time=None, herd_timeout=None):
# async with await self.client.pipeline() as pipeline:
# for key, value in data.items():
# identity = self._gen_identity(key, param)
# expected_expired_ts = int(time.time())
# if expire_time:
# expected_expired_ts += expire_time
# expected_expired_ts += herd_timeout or self.default_herd_timeout
# value = self._pack([value, expected_expired_ts])
# await pipeline.set(identity, value, ex=expire_time)
# return await pipeline.execute()
#
# async def get(self, key, param=None, extend_herd_timeout=None):
# """
# Uses key or identity generated from key and param to get cached
# content and expiratiom time.
# Uses time.now() to check expiration. If not expired, returns unpacked
# content. Otherwise returns None and sets cache with extended timeout
# """
# identity = self._gen_identity(key, param)
# res = await self.client.get(identity)
# if res:
# res, timeout = self._unpack(res)
# now = int(time.time())
# if timeout <= now:
# extend_timeout = extend_herd_timeout or self.extend_herd_timeout
# expected_expired_ts = now + extend_timeout
# value = self._pack([res, expected_expired_ts])
# await self.client.set(identity, value, extend_timeout)
# return None
# return res
. Output only the next line. | 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.flushdb()
cache = Cache(r, self.app)
await cache.set(self.key, self.expensive_work(self.data),
self.data, expire_time=1)
exists = await cache.exist(self.key, self.data)
assert exists is True
await asyncio.sleep(1.1, loop=event_loop)
exists = await cache.exist(self.key, self.data)
assert exists is False
class TestHerdCache:
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(self, r):
await r.flushdb()
<|code_end|>
using the current file's imports:
import asyncio
import pytest
import time
from aredis.cache import Cache, HerdCache
and any relevant context from other files:
# Path: aredis/cache.py
# class Cache(BasicCache):
# """Provides basic caching"""
#
# async def get(self, key, param=None):
# identity = self._gen_identity(key, param)
# res = await self.client.get(identity)
# if res:
# res = self._unpack(res)
# return res
#
# async def set(self, key, value, param=None, expire_time=None):
# identity = self._gen_identity(key, param)
# value = self._pack(value)
# return await self.client.set(identity, value, ex=expire_time)
#
# async def set_many(self, data, param=None, expire_time=None):
# async with await self.client.pipeline() as pipeline:
# for key, value in data.items():
# identity = self._gen_identity(key, param)
# value = self._pack(value)
# await pipeline.set(identity, value, expire_time)
# return await pipeline.execute()
#
# class HerdCache(BasicCache):
# """
# Cache that handles thundering herd problem
# (https://en.wikipedia.org/wiki/Thundering_herd_problem)
# by cacheing expiration time in set instead of directly using expire
# operation of redis.
# This kind of cache is suitable for low consistency scene where update
# operations are expensive.
# """
#
# def __init__(self, client, app='', identity_generator_class=IdentityGenerator,
# compressor_class=Compressor, serializer_class=Serializer,
# default_herd_timeout=1, extend_herd_timeout=1, encoding='utf-8'):
# self.default_herd_timeout = default_herd_timeout
# self.extend_herd_timeout = extend_herd_timeout
# super(HerdCache, self).__init__(client, app, identity_generator_class,
# compressor_class, serializer_class,
# encoding)
#
# async def set(self, key, value, param=None, expire_time=None, herd_timeout=None):
# """
# Uses key and param to generate identity and pack the content,
# expire the key within real_timeout if expire_time is given.
# real_timeout is equal to the sum of expire_time and herd_time.
# The content is cached with expire_time.
# """
# identity = self._gen_identity(key, param)
# expected_expired_ts = int(time.time())
# if expire_time:
# expected_expired_ts += expire_time
# expected_expired_ts += herd_timeout or self.default_herd_timeout
# value = self._pack([value, expected_expired_ts])
# return await self.client.set(identity, value, ex=expire_time)
#
# async def set_many(self, data, param=None, expire_time=None, herd_timeout=None):
# async with await self.client.pipeline() as pipeline:
# for key, value in data.items():
# identity = self._gen_identity(key, param)
# expected_expired_ts = int(time.time())
# if expire_time:
# expected_expired_ts += expire_time
# expected_expired_ts += herd_timeout or self.default_herd_timeout
# value = self._pack([value, expected_expired_ts])
# await pipeline.set(identity, value, ex=expire_time)
# return await pipeline.execute()
#
# async def get(self, key, param=None, extend_herd_timeout=None):
# """
# Uses key or identity generated from key and param to get cached
# content and expiratiom time.
# Uses time.now() to check expiration. If not expired, returns unpacked
# content. Otherwise returns None and sets cache with extended timeout
# """
# identity = self._gen_identity(key, param)
# res = await self.client.get(identity)
# if res:
# res, timeout = self._unpack(res)
# now = int(time.time())
# if timeout <= now:
# extend_timeout = extend_herd_timeout or self.extend_herd_timeout
# expected_expired_ts = now + extend_timeout
# value = self._pack([res, expected_expired_ts])
# await self.client.set(identity, value, extend_timeout)
# return None
# return res
. Output only the next line. | 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,
dict_merge,
bool_ok)
and context from other files:
# Path: aredis/utils.py
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
, which may contain function names, class names, or code. Output only the next line. | '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-require-full-coverage config, useful for clusters
without the CONFIG command (like aws)
:nodemanager_follow_cluster:
The node manager will during initialization try the last set of nodes that
it was operating on. This will allow the client to drift along side the cluster
if the cluster nodes move around a slot.
"""
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.reinitialize_steps = reinitialize_steps or 25
self._skip_full_coverage_check = skip_full_coverage_check
self.nodemanager_follow_cluster = nodemanager_follow_cluster
if not self.startup_nodes:
raise RedisClusterException("No startup nodes provided")
def encode(self, value):
"""Returns a bytestring representation of the value"""
if isinstance(value, bytes):
return value
elif isinstance(value, int):
<|code_end|>
. Use current file imports:
import random
from aredis.utils import (b, hash_slot)
from aredis.exceptions import (ConnectionError,
RedisClusterException)
from aredis.client import StrictRedis
and context (classes, functions, or code) from other files:
# Path: aredis/utils.py
# _C_EXTENSION_SPEEDUP = False
# _C_EXTENSION_SPEEDUP = True
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
# def b(x):
# def nativestr(x):
# def iteritems(x):
# def iterkeys(x):
# def itervalues(x):
# def ban_python_version_lt(min_version):
# def decorator(func):
# def _inner(*args, **kwargs):
# def __init__(self):
# def set(self, value):
# def get(self):
# def string_keys_to_dict(key_string, callback):
# def list_keys_to_dict(key_list, callback):
# def dict_merge(*dicts):
# def bool_ok(response):
# def list_or_args(keys, args):
# def int_or_none(response):
# def pairs_to_dict(response):
# def merge_result(res):
# def first_key(res):
# def blocked_command(self, command):
# def clusterdown_wrapper(func):
# async def inner(*args, **kwargs):
# def _crc16(data):
# def _hash_slot(key):
# class dummy:
# class NodeFlag:
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
. Output only the next line. | 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.reinitialize_steps = reinitialize_steps or 25
self._skip_full_coverage_check = skip_full_coverage_check
self.nodemanager_follow_cluster = nodemanager_follow_cluster
if not self.startup_nodes:
raise RedisClusterException("No startup nodes provided")
def encode(self, value):
"""Returns a bytestring representation of the value"""
if isinstance(value, bytes):
return value
elif isinstance(value, int):
value = b(str(value))
elif isinstance(value, float):
value = b(repr(value))
elif not isinstance(value, str):
value = str(value)
if isinstance(value, str):
value = value.encode()
return value
def keyslot(self, key):
"""Calculates keyslot for a given key"""
key = self.encode(key)
<|code_end|>
, determine the next line of code. You have imports:
import random
from aredis.utils import (b, hash_slot)
from aredis.exceptions import (ConnectionError,
RedisClusterException)
from aredis.client import StrictRedis
and context (class names, function names, or code) available:
# Path: aredis/utils.py
# _C_EXTENSION_SPEEDUP = False
# _C_EXTENSION_SPEEDUP = True
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
# def b(x):
# def nativestr(x):
# def iteritems(x):
# def iterkeys(x):
# def itervalues(x):
# def ban_python_version_lt(min_version):
# def decorator(func):
# def _inner(*args, **kwargs):
# def __init__(self):
# def set(self, value):
# def get(self):
# def string_keys_to_dict(key_string, callback):
# def list_keys_to_dict(key_list, callback):
# def dict_merge(*dicts):
# def bool_ok(response):
# def list_or_args(keys, args):
# def int_or_none(response):
# def pairs_to_dict(response):
# def merge_result(res):
# def first_key(res):
# def blocked_command(self, command):
# def clusterdown_wrapper(func):
# async def inner(*args, **kwargs):
# def _crc16(data):
# def _hash_slot(key):
# class dummy:
# class NodeFlag:
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
. Output only the next line. | 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 all startup nodes what the
current cluster configuration is.
TODO: Currently the last node will have the last say about how the configuration is setup.
Maybe it should stop to try after it have correctly covered all slots or when one node is reached
and it could execute CLUSTER SLOTS command.
"""
nodes_cache = {}
tmp_slots = {}
all_slots_covered = False
disagreements = []
startup_nodes_reachable = False
nodes = self.orig_startup_nodes
# With this option the client will attempt to connect to any of the previous set of nodes instead of the original set of nodes
if self.nodemanager_follow_cluster:
nodes = self.startup_nodes
for node in nodes:
try:
r = self.get_redis_link(host=node['host'], port=node['port'])
cluster_slots = await r.cluster_slots()
startup_nodes_reachable = True
<|code_end|>
, predict the immediate next line with the help of imports:
import random
from aredis.utils import (b, hash_slot)
from aredis.exceptions import (ConnectionError,
RedisClusterException)
from aredis.client import StrictRedis
and context (classes, functions, sometimes code) from other files:
# Path: aredis/utils.py
# _C_EXTENSION_SPEEDUP = False
# _C_EXTENSION_SPEEDUP = True
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
# def b(x):
# def nativestr(x):
# def iteritems(x):
# def iterkeys(x):
# def itervalues(x):
# def ban_python_version_lt(min_version):
# def decorator(func):
# def _inner(*args, **kwargs):
# def __init__(self):
# def set(self, value):
# def get(self):
# def string_keys_to_dict(key_string, callback):
# def list_keys_to_dict(key_list, callback):
# def dict_merge(*dicts):
# def bool_ok(response):
# def list_or_args(keys, args):
# def int_or_none(response):
# def pairs_to_dict(response):
# def merge_result(res):
# def first_key(res):
# def blocked_command(self, command):
# def clusterdown_wrapper(func):
# async def inner(*args, **kwargs):
# def _crc16(data):
# def _hash_slot(key):
# class dummy:
# class NodeFlag:
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
. Output only the next line. | 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, **connection_kwargs):
"""
:skip_full_coverage_check:
Skips the check of cluster-require-full-coverage config, useful for clusters
without the CONFIG command (like aws)
:nodemanager_follow_cluster:
The node manager will during initialization try the last set of nodes that
it was operating on. This will allow the client to drift along side the cluster
if the cluster nodes move around a slot.
"""
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.reinitialize_steps = reinitialize_steps or 25
self._skip_full_coverage_check = skip_full_coverage_check
self.nodemanager_follow_cluster = nodemanager_follow_cluster
if not self.startup_nodes:
<|code_end|>
with the help of current file imports:
import random
from aredis.utils import (b, hash_slot)
from aredis.exceptions import (ConnectionError,
RedisClusterException)
from aredis.client import StrictRedis
and context from other files:
# Path: aredis/utils.py
# _C_EXTENSION_SPEEDUP = False
# _C_EXTENSION_SPEEDUP = True
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
# def b(x):
# def nativestr(x):
# def iteritems(x):
# def iterkeys(x):
# def itervalues(x):
# def ban_python_version_lt(min_version):
# def decorator(func):
# def _inner(*args, **kwargs):
# def __init__(self):
# def set(self, value):
# def get(self):
# def string_keys_to_dict(key_string, callback):
# def list_keys_to_dict(key_list, callback):
# def dict_merge(*dicts):
# def bool_ok(response):
# def list_or_args(keys, args):
# def int_or_none(response):
# def pairs_to_dict(response):
# def merge_result(res):
# def first_key(res):
# def blocked_command(self, command):
# def clusterdown_wrapper(func):
# async def inner(*args, **kwargs):
# def _crc16(data):
# def _hash_slot(key):
# class dummy:
# class NodeFlag:
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | 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 import StrictRedis
from tornado.web import RequestHandler, Application
from tornado.httpserver import HTTPServer
from tornado.platform.asyncio import AsyncIOMainLoop
and context (classes, functions, sometimes code) from other files:
# Path: aredis/client.py
# class StrictRedis(*mixins):
# """
# Implementation of the Redis protocol.
#
# This abstract class provides a Python interface to all Redis commands
# and an implementation of the Redis protocol.
#
# Connection and Pipeline derive from this, implementing how
# the commands are sent and received to the Redis server
# """
#
# RESPONSE_CALLBACKS = dict_merge(*[mixin.RESPONSE_CALLBACKS for mixin in mixins])
#
# @classmethod
# def from_url(cls, url, db=None, **kwargs):
# """
# Return a Redis client object configured from the given URL, which must
# use either `the ``redis://`` scheme
# <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ for RESP
# connections or the ``unix://`` scheme for Unix domain sockets.
#
# For example:
#
# redis://[:password]@localhost:6379/0
# unix://[:password]@/path/to/socket.sock?db=0
#
# There are several ways to specify a database number. The parse function
# will return the first specified option:
# 1. A ``db`` querystring option, e.g. redis://localhost?db=0
# 2. If using the redis:// scheme, the path argument of the url, e.g.
# redis://localhost/0
# 3. The ``db`` argument to this function.
#
# If none of these options are specified, db=0 is used.
#
# Any additional querystring arguments and keyword arguments will be
# passed along to the ConnectionPool class's initializer. In the case
# of conflicting arguments, querystring arguments always win.
# """
# connection_pool = ConnectionPool.from_url(url, db=db, **kwargs)
# return cls(connection_pool=connection_pool)
#
# def __init__(self, host='localhost', port=6379,
# db=0, password=None, stream_timeout=None,
# connect_timeout=None, connection_pool=None,
# unix_socket_path=None, encoding='utf-8',
# decode_responses=False, ssl=False, ssl_context=None,
# ssl_keyfile=None, ssl_certfile=None,
# ssl_cert_reqs=None, ssl_ca_certs=None,
# max_connections=None, retry_on_timeout=False,
# max_idle_time=0, idle_check_interval=1,
# loop=None, **kwargs):
# if not connection_pool:
# kwargs = {
# 'db': db,
# 'password': password,
# 'encoding': encoding,
# 'stream_timeout': stream_timeout,
# 'connect_timeout': connect_timeout,
# 'max_connections': max_connections,
# 'retry_on_timeout': retry_on_timeout,
# 'decode_responses': decode_responses,
# 'max_idle_time': max_idle_time,
# 'idle_check_interval': idle_check_interval,
# 'loop': loop
# }
# # based on input, setup appropriate connection args
# if unix_socket_path is not None:
# kwargs.update({
# 'path': unix_socket_path,
# 'connection_class': UnixDomainSocketConnection
# })
# else:
# # TCP specific options
# kwargs.update({
# 'host': host,
# 'port': port
# })
# if ssl_context is not None:
# kwargs['ssl_context'] = ssl_context
# elif ssl:
# ssl_context = RedisSSLContext(ssl_keyfile, ssl_certfile, ssl_cert_reqs, ssl_ca_certs).get()
# kwargs['ssl_context'] = ssl_context
# connection_pool = ConnectionPool(**kwargs)
# self.connection_pool = connection_pool
# self._use_lua_lock = None
#
# self.response_callbacks = self.__class__.RESPONSE_CALLBACKS.copy()
#
# def __repr__(self):
# return "{}<{}>".format(type(self).__name__, repr(self.connection_pool))
#
# def set_response_callback(self, command, callback):
# """Sets a custom Response Callback"""
# self.response_callbacks[command] = callback
#
# # COMMAND EXECUTION AND PROTOCOL PARSING
# async def execute_command(self, *args, **options):
# """Executes a command and returns a parsed response"""
# pool = self.connection_pool
# command_name = args[0]
# connection = pool.get_connection()
# try:
# await connection.send_command(*args)
# return await self.parse_response(connection, command_name, **options)
# except CancelledError:
# # do not retry when coroutine is cancelled
# connection.disconnect()
# raise
# except (ConnectionError, TimeoutError) as e:
# connection.disconnect()
# if not connection.retry_on_timeout and isinstance(e, TimeoutError):
# raise
# await connection.send_command(*args)
# return await self.parse_response(connection, command_name, **options)
# finally:
# pool.release(connection)
#
# async def parse_response(self, connection, command_name, **options):
# """Parses a response from the Redis server"""
# response = await connection.read_response()
# if command_name in self.response_callbacks:
# callback = self.response_callbacks[command_name]
# return callback(response, **options)
# return response
#
# async def pipeline(self, transaction=True, shard_hint=None):
# """
# Returns a new pipeline object that can queue multiple commands for
# later execution. ``transaction`` indicates whether all commands
# should be executed atomically. Apart from making a group of operations
# atomic, pipelines are useful for reducing the back-and-forth overhead
# between the client and server.
# """
# from aredis.pipeline import StrictPipeline
# pipeline = StrictPipeline(self.connection_pool, self.response_callbacks,
# transaction, shard_hint)
# await pipeline.reset()
# return pipeline
. Output only the next line. | 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_messages=True)
# 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.data,
# pattern=self.pattern)
#
# # 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(p) is None
# assert self.message == self.make_message('pmessage', self.channel,
# new_data,
# pattern=self.pattern)
#
#
class TestPubSubRedisDown:
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_channel_subscribe(self, r):
r = aredis.StrictRedis(host='localhost', port=6390)
p = r.pubsub()
<|code_end|>
. Use current file imports:
import asyncio
import pickle
import time
import pytest
import aredis
from aredis.exceptions import ConnectionError
from aredis.utils import b
from .conftest import skip_if_server_version_lt
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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(p) is None
# assert self.message == self.make_message('pmessage', self.channel,
# new_data,
# pattern=self.pattern)
#
#
class TestPubSubRedisDown:
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_channel_subscribe(self, r):
r = aredis.StrictRedis(host='localhost', port=6390)
p = r.pubsub()
with pytest.raises(ConnectionError):
await p.subscribe('foo')
class TestPubSubPubSubSubcommands:
@skip_if_server_version_lt('2.8.0')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_pubsub_channels(self, r):
p = r.pubsub(ignore_subscribe_messages=True)
await p.subscribe('foo', 'bar', 'baz', 'quux')
channels = sorted(await r.pubsub_channels())
<|code_end|>
. Use current file imports:
(import asyncio
import pickle
import time
import pytest
import aredis
from aredis.exceptions import ConnectionError
from aredis.utils import b
from .conftest import skip_if_server_version_lt)
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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.data,
# pattern=self.pattern)
#
# # 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(p) is None
# assert self.message == self.make_message('pmessage', self.channel,
# new_data,
# pattern=self.pattern)
#
#
class TestPubSubRedisDown:
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_channel_subscribe(self, r):
r = aredis.StrictRedis(host='localhost', port=6390)
p = r.pubsub()
with pytest.raises(ConnectionError):
await p.subscribe('foo')
class TestPubSubPubSubSubcommands:
<|code_end|>
, determine the next line of code. You have imports:
import asyncio
import pickle
import time
import pytest
import aredis
from aredis.exceptions import ConnectionError
from aredis.utils import b
from .conftest import skip_if_server_version_lt
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | @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 pool.connection_class == aredis.Connection
assert pool.connection_kwargs == {
'host': 'localhost',
'port': 6379,
'db': 2,
'stream_timeout': 20.0,
'connect_timeout': 10.0,
'password': None,
}
def test_boolean_parsing(self):
for expected, value in (
(None, None),
(None, ''),
(False, 0), (False, '0'),
(False, 'f'), (False, 'F'), (False, 'False'),
(False, 'n'), (False, 'N'), (False, 'No'),
(True, 1), (True, '1'),
(True, 'y'), (True, 'Y'), (True, 'Yes'),
):
<|code_end|>
using the current file's imports:
import os
import pytest
import aredis
import re
import asyncio
import warnings
import ssl
from aredis.pool import to_bool
from aredis.exceptions import (ConnectionError, RedisError,
BusyLoadingError, ReadOnlyError)
from .conftest import skip_if_server_version_lt
and any relevant context from other files:
# Path: aredis/pool.py
# def to_bool(value):
# if value is None or value == '':
# return None
# if isinstance(value, str) and value.upper() in FALSE_STRINGS:
# return False
# return bool(value)
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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(
connection_class=connection_class,
max_connections=max_connections,
**connection_kwargs)
return pool
def test_connection_creation(self):
connection_kwargs = {'foo': 'bar', 'biz': 'baz'}
pool = self.get_pool(connection_kwargs=connection_kwargs)
connection = pool.get_connection()
assert isinstance(connection, DummyConnection)
assert connection.kwargs == connection_kwargs
def test_multiple_connections(self):
pool = self.get_pool()
c1 = pool.get_connection()
c2 = pool.get_connection()
assert c1 != c2
def test_max_connections(self):
pool = self.get_pool(max_connections=2)
pool.get_connection()
pool.get_connection()
<|code_end|>
. Use current file imports:
import os
import pytest
import aredis
import re
import asyncio
import warnings
import ssl
from aredis.pool import to_bool
from aredis.exceptions import (ConnectionError, RedisError,
BusyLoadingError, ReadOnlyError)
from .conftest import skip_if_server_version_lt
and context (classes, functions, or code) from other files:
# Path: aredis/pool.py
# def to_bool(value):
# if value is None or value == '':
# return None
# if isinstance(value, str) and value.upper() in FALSE_STRINGS:
# return False
# return bool(value)
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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.CERT_NONE
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_context.verify_mode == ssl.CERT_OPTIONAL
with pytest.raises(TypeError) as e:
pool = aredis.ConnectionPool.from_url(
'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(forbid_global_loop=True)
async def test_on_connect_error(self, 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 = aredis.StrictRedis(db=9999, loop=event_loop)
# an error should be raised on connect
<|code_end|>
with the help of current file imports:
import os
import pytest
import aredis
import re
import asyncio
import warnings
import ssl
from aredis.pool import to_bool
from aredis.exceptions import (ConnectionError, RedisError,
BusyLoadingError, ReadOnlyError)
from .conftest import skip_if_server_version_lt
and context from other files:
# Path: aredis/pool.py
# def to_bool(value):
# if value is None or value == '':
# return None
# if isinstance(value, str) and value.upper() in FALSE_STRINGS:
# return False
# return bool(value)
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
, which may contain function names, class names, or code. Output only the next line. | 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(forbid_global_loop=True)
async def test_on_connect_error(self, 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 = aredis.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
@skip_if_server_version_lt('2.8.8')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_busy_loading_disconnects_socket(self, event_loop):
"""
If Redis raises a LOADING error, the connection should be
disconnected and a BusyLoadingError raised
"""
client = aredis.StrictRedis(loop=event_loop)
<|code_end|>
, determine the next line of code. You have imports:
import os
import pytest
import aredis
import re
import asyncio
import warnings
import ssl
from aredis.pool import to_bool
from aredis.exceptions import (ConnectionError, RedisError,
BusyLoadingError, ReadOnlyError)
from .conftest import skip_if_server_version_lt
and context (class names, function names, or code) available:
# Path: aredis/pool.py
# def to_bool(value):
# if value is None or value == '':
# return None
# if isinstance(value, str) and value.upper() in FALSE_STRINGS:
# return False
# return bool(value)
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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 len(pool._available_connections) == 0
@skip_if_server_version_lt('2.8.8')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_busy_loading_from_pipeline(self, event_loop):
"""
BusyLoadingErrors should be raised from a pipeline execution
regardless of the raise_on_error flag.
"""
client = aredis.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
@skip_if_server_version_lt('2.8.8')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_read_only_error(self, event_loop):
"READONLY errors get turned in ReadOnlyError exceptions"
client = aredis.StrictRedis(loop=event_loop)
<|code_end|>
with the help of current file imports:
import os
import pytest
import aredis
import re
import asyncio
import warnings
import ssl
from aredis.pool import to_bool
from aredis.exceptions import (ConnectionError, RedisError,
BusyLoadingError, ReadOnlyError)
from .conftest import skip_if_server_version_lt
and context from other files:
# Path: aredis/pool.py
# def to_bool(value):
# if value is None or value == '':
# return None
# if isinstance(value, str) and value.upper() in FALSE_STRINGS:
# return False
# return bool(value)
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
, which may contain function names, class names, or code. Output only the next line. | 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_context.verify_mode == ssl.CERT_OPTIONAL
with pytest.raises(TypeError) as e:
pool = aredis.ConnectionPool.from_url(
'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(forbid_global_loop=True)
async def test_on_connect_error(self, 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 = aredis.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
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import pytest
import aredis
import re
import asyncio
import warnings
import ssl
from aredis.pool import to_bool
from aredis.exceptions import (ConnectionError, RedisError,
BusyLoadingError, ReadOnlyError)
from .conftest import skip_if_server_version_lt
and context:
# Path: aredis/pool.py
# def to_bool(value):
# if value is None or value == '':
# return None
# if isinstance(value, str) and value.upper() in FALSE_STRINGS:
# return False
# return bool(value)
#
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
which might include code, classes, or functions. Output only the next line. | @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[2] if len(node) > 2 else '',
'server_type': 'slave'
}
res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
res[(min_slot, max_slot)][0]['server_type'] = 'master'
return res
class ClusterCommandMixin:
NODES_FLAGS = dict_merge({
'CLUSTER INFO': NodeFlag.ALL_NODES,
'CLUSTER COUNTKEYSINSLOT': NodeFlag.SLOT_ID
},
list_keys_to_dict(
['CLUSTER NODES', 'CLUSTER SLOTS'], NodeFlag.RANDOM
)
)
RESPONSE_CALLBACKS = {
<|code_end|>
. Use current file imports:
from aredis.utils import (bool_ok,
nativestr,
NodeFlag,
list_keys_to_dict,
dict_merge)
from aredis.exceptions import (RedisError,
ClusterError)
and context (classes, functions, or code) from other files:
# Path: aredis/utils.py
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ClusterError(RedisError):
# pass
. Output only the next line. | '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 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[2] if len(node) > 2 else '',
'server_type': 'slave'
}
res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
res[(min_slot, max_slot)][0]['server_type'] = 'master'
return res
class ClusterCommandMixin:
NODES_FLAGS = dict_merge({
<|code_end|>
, predict the immediate next line with the help of imports:
from aredis.utils import (bool_ok,
nativestr,
NodeFlag,
list_keys_to_dict,
dict_merge)
from aredis.exceptions import (RedisError,
ClusterError)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/utils.py
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ClusterError(RedisError):
# pass
. Output only the next line. | '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 = slot_info[2:]
parse_node = lambda node: {
'host': node[0],
'port': node[1],
'node_id': node[2] if len(node) > 2 else '',
'server_type': 'slave'
}
res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
res[(min_slot, max_slot)][0]['server_type'] = 'master'
return res
class ClusterCommandMixin:
NODES_FLAGS = dict_merge({
'CLUSTER INFO': NodeFlag.ALL_NODES,
'CLUSTER COUNTKEYSINSLOT': NodeFlag.SLOT_ID
},
<|code_end|>
using the current file's imports:
from aredis.utils import (bool_ok,
nativestr,
NodeFlag,
list_keys_to_dict,
dict_merge)
from aredis.exceptions import (RedisError,
ClusterError)
and any relevant context from other files:
# Path: aredis/utils.py
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ClusterError(RedisError):
# pass
. Output only the next line. | 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 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[2] if len(node) > 2 else '',
'server_type': 'slave'
}
res[(min_slot, max_slot)] = [parse_node(node) for node in nodes]
res[(min_slot, max_slot)][0]['server_type'] = 'master'
return res
class ClusterCommandMixin:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from aredis.utils import (bool_ok,
nativestr,
NodeFlag,
list_keys_to_dict,
dict_merge)
from aredis.exceptions import (RedisError,
ClusterError)
and context:
# Path: aredis/utils.py
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ClusterError(RedisError):
# pass
which might include code, classes, or functions. Output only the next line. | 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_epoch(self, node_id, epoch):
"""
Set the configuration epoch in a new node
Sends to specefied node
"""
return await self.execute_command('CLUSTER SET-CONFIG-EPOCH', epoch, node_id=node_id)
async def cluster_setslot(self, node_id, slot_id, state):
"""
Bind an hash slot to a specific node
Sends to specified node
"""
if state.upper() in {'IMPORTING', 'MIGRATING', 'NODE'} and node_id is not None:
return await self.execute_command('CLUSTER SETSLOT', slot_id, state, node_id)
elif state.upper() == 'STABLE':
return await self.execute_command('CLUSTER SETSLOT', slot_id, 'STABLE')
else:
<|code_end|>
, predict the immediate next line with the help of imports:
from aredis.utils import (bool_ok,
nativestr,
NodeFlag,
list_keys_to_dict,
dict_merge)
from aredis.exceptions import (RedisError,
ClusterError)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/utils.py
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ClusterError(RedisError):
# pass
. Output only the next line. | 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
"""
return await self.execute_command('CLUSTER COUNTKEYSINSLOT', slot_id)
async def cluster_delslots(self, *slots):
"""
Set hash slots as unbound in the cluster.
It determines by it self what node the slot is in and sends it there
Returns a list of the results for each processed slot.
"""
cluster_nodes = self._nodes_slots_to_slots_nodes(await self.cluster_nodes())
res = list()
for slot in slots:
res.append(await self.execute_command('CLUSTER DELSLOTS', slot, node_id=cluster_nodes[slot]))
return res
async def cluster_failover(self, node_id, option):
"""
Forces a slave to perform a manual failover of its master
Sends to specefied node
"""
if not isinstance(option, str) or option.upper() not in {'FORCE', 'TAKEOVER'}:
<|code_end|>
. Use current file imports:
from aredis.utils import (bool_ok,
nativestr,
NodeFlag,
list_keys_to_dict,
dict_merge)
from aredis.exceptions import (RedisError,
ClusterError)
and context (classes, functions, or code) from other files:
# Path: aredis/utils.py
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ClusterError(RedisError):
# pass
. Output only the next line. | 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)) with N being the number of items already into the stream.
:param name: name of the stream
:param entry: key-values to be appended to the stream
:param max_len: max length of the stream
length will not be limited max_len is set to None
notice: max_len should be int greater than 0,
if set to 0 or negative, the stream length will not be limited
:param stream_id: id of the options appended to the stream.
The XADD command will auto-generate a unique id for you
if the id argument specified is the * character.
ID are specified by two numbers separated by a "-" character
:param approximate: whether redis will limit
the stream with given max length exactly, if set to True,
there will be a few tens of entries more,
but never less than 1000 items
:return: id auto generated or the specified id given.
notice: specified id without "-" character will be completed like "id-0"
"""
pieces = []
if max_len is not None:
if not isinstance(max_len, int) or max_len < 1:
<|code_end|>
, generate the next line using the imports in this file:
from aredis.exceptions import RedisError
from aredis.utils import (dict_merge, pairs_to_dict,
string_keys_to_dict, bool_ok)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | 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:
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(response):
res = pairs_to_dict(response)
if res['first-entry'] and len(res['first-entry']) > 0:
res['first-entry'][1] = pairs_to_dict(res['first-entry'][1])
if res['last-entry'] and len(res['last-entry']) > 0:
res['last-entry'][1] = pairs_to_dict(res['last-entry'][1])
return res
class StreamsCommandMixin:
<|code_end|>
, determine the next line of code. You have imports:
from aredis.exceptions import RedisError
from aredis.utils import (dict_merge, pairs_to_dict,
string_keys_to_dict, bool_ok)
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | 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[0], kv_dict))
return result
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):
<|code_end|>
, generate the next line using the imports in this file:
from aredis.exceptions import RedisError
from aredis.utils import (dict_merge, pairs_to_dict,
string_keys_to_dict, bool_ok)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | 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 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(response):
res = pairs_to_dict(response)
if res['first-entry'] and len(res['first-entry']) > 0:
res['first-entry'][1] = pairs_to_dict(res['first-entry'][1])
if res['last-entry'] and len(res['last-entry']) > 0:
res['last-entry'][1] = pairs_to_dict(res['last-entry'][1])
return res
class StreamsCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
<|code_end|>
. Use current file imports:
(from aredis.exceptions import RedisError
from aredis.utils import (dict_merge, pairs_to_dict,
string_keys_to_dict, bool_ok))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | 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(response):
res = pairs_to_dict(response)
if res['first-entry'] and len(res['first-entry']) > 0:
res['first-entry'][1] = pairs_to_dict(res['first-entry'][1])
if res['last-entry'] and len(res['last-entry']) > 0:
res['last-entry'][1] = pairs_to_dict(res['last-entry'][1])
return res
class StreamsCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict('XREVRANGE XRANGE', stream_list),
string_keys_to_dict('XREAD XREADGROUP', multi_stream_list),
{
'XINFO GROUPS': list_of_pairs_to_dict,
'XINFO STREAM': parse_xinfo_stream,
'XINFO CONSUMERS': list_of_pairs_to_dict,
<|code_end|>
. Use current file imports:
(from aredis.exceptions import RedisError
from aredis.utils import (dict_merge, pairs_to_dict,
string_keys_to_dict, bool_ok))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | '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.
Since it is a single-key solution, the migration problem also do no matter.
Please read these article below before using this cluster lock in your app.
https://redis.io/topics/distlock
http://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html
http://antirez.com/news/101
"""
def __init__(self, *args, **kwargs):
super(ClusterLock, self).__init__(*args, **kwargs)
if not self.timeout:
raise LockError('timeout must be provided for cluster lock')
async def check_lock_in_slaves(self, token):
node_manager = self.redis.connection_pool.nodes
slot = node_manager.keyslot(self.name)
master_node_id = node_manager.node_from_slot(slot)['node_id']
slave_nodes = await self.redis.cluster_slaves(master_node_id)
count, quorum = 0, (len(slave_nodes) // 2) + 1
conn_kwargs = self.redis.connection_pool.connection_kwargs
conn_kwargs['readonly'] = True
for node in slave_nodes:
try:
# todo: a little bit dirty here, try to reuse StrictRedis later
# todo: it may be optimized by using a new connection pool
<|code_end|>
using the current file's imports:
import asyncio
import time as mod_time
import uuid
import warnings
import contextvars
from aredis.connection import ClusterConnection
from aredis.exceptions import LockError, WatchError
from aredis.utils import b, dummy
and any relevant context from other files:
# Path: aredis/connection.py
# class ClusterConnection(Connection):
# "Manages TCP communication to and from a Redis server"
# description = "ClusterConnection<host={host},port={port}>"
#
# def __init__(self, *args, **kwargs):
# self.readonly = kwargs.pop('readonly', False)
# super(ClusterConnection, self).__init__(*args, **kwargs)
#
# async def on_connect(self):
# """
# Initialize the connection, authenticate and select a database and send READONLY if it is
# set during object initialization.
# """
# if self.db:
# warnings.warn('SELECT DB is not allowed in cluster mode')
# self.db = ''
# await super(ClusterConnection, self).on_connect()
# if self.readonly:
# await self.send_command('READONLY')
# if nativestr(await self.read_response()) != 'OK':
# raise ConnectionError('READONLY command failed')
#
# Path: aredis/exceptions.py
# class LockError(RedisError, ValueError):
# """Errors acquiring or releasing a lock"""
# # NOTE: For backwards compatability, this class derives from ValueError.
# # This was originally chosen to behave like threading.Lock.
# pass
#
# class WatchError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# class dummy:
# """
# Instances of this class can be used as an attribute container.
# """
#
# def __init__(self):
# self.token = None
#
# def set(self, value):
# self.token = value
#
# def get(self):
# return self.token
. Output only the next line. | 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, thread-1 has not yet completed. redis expires the lock
key.
time: 5, thread-2 acquired `my-lock` now that it's available.
thread-2 sets the token to "xyz"
time: 6, thread-1 finishes its work and calls release(). if the
token is *not* stored in thread local storage, then
thread-1 would see the token value as "xyz" and would be
able to successfully release the thread-2's lock.
In some use cases it's necessary to disable thread local storage. For
example, if you have code where one thread acquires a lock and passes
that lock instance to a worker thread to release later. If thread
local storage isn't disabled in this case, the worker thread won't see
the token set by the thread that acquired the lock. Our assumption
is that these cases aren't common and as such default to using
thread local storage.
"""
self.redis = redis
self.name = name
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 dummy()
if self.timeout and self.sleep > self.timeout:
<|code_end|>
with the help of current file imports:
import asyncio
import time as mod_time
import uuid
import warnings
import contextvars
from aredis.connection import ClusterConnection
from aredis.exceptions import LockError, WatchError
from aredis.utils import b, dummy
and context from other files:
# Path: aredis/connection.py
# class ClusterConnection(Connection):
# "Manages TCP communication to and from a Redis server"
# description = "ClusterConnection<host={host},port={port}>"
#
# def __init__(self, *args, **kwargs):
# self.readonly = kwargs.pop('readonly', False)
# super(ClusterConnection, self).__init__(*args, **kwargs)
#
# async def on_connect(self):
# """
# Initialize the connection, authenticate and select a database and send READONLY if it is
# set during object initialization.
# """
# if self.db:
# warnings.warn('SELECT DB is not allowed in cluster mode')
# self.db = ''
# await super(ClusterConnection, self).on_connect()
# if self.readonly:
# await self.send_command('READONLY')
# if nativestr(await self.read_response()) != 'OK':
# raise ConnectionError('READONLY command failed')
#
# Path: aredis/exceptions.py
# class LockError(RedisError, ValueError):
# """Errors acquiring or releasing a lock"""
# # NOTE: For backwards compatability, this class derives from ValueError.
# # This was originally chosen to behave like threading.Lock.
# pass
#
# class WatchError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# class dummy:
# """
# Instances of this class can be used as an attribute container.
# """
#
# def __init__(self):
# self.token = None
#
# def set(self, value):
# self.token = value
#
# def get(self):
# return self.token
, which may contain function names, class names, or code. Output only the next line. | 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 None:
raise LockError("Cannot extend an unlocked lock")
if self.timeout is None:
raise LockError("Cannot extend a lock with no timeout")
return await self.do_extend(additional_time)
async def do_extend(self, additional_time):
pipe = await self.redis.pipeline()
await pipe.watch(self.name)
lock_value = await pipe.get(self.name)
if lock_value != self.local.get():
raise LockError("Cannot extend a lock that's no longer owned")
expiration = await pipe.pttl(self.name)
if expiration is None or expiration < 0:
# Redis evicted the lock key between the previous get() and now
# we'll handle this when we call pexpire()
expiration = 0
pipe.multi()
await pipe.pexpire(self.name, expiration + int(additional_time * 1000))
try:
response = await pipe.execute()
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import time as mod_time
import uuid
import warnings
import contextvars
from aredis.connection import ClusterConnection
from aredis.exceptions import LockError, WatchError
from aredis.utils import b, dummy
and context (classes, functions, sometimes code) from other files:
# Path: aredis/connection.py
# class ClusterConnection(Connection):
# "Manages TCP communication to and from a Redis server"
# description = "ClusterConnection<host={host},port={port}>"
#
# def __init__(self, *args, **kwargs):
# self.readonly = kwargs.pop('readonly', False)
# super(ClusterConnection, self).__init__(*args, **kwargs)
#
# async def on_connect(self):
# """
# Initialize the connection, authenticate and select a database and send READONLY if it is
# set during object initialization.
# """
# if self.db:
# warnings.warn('SELECT DB is not allowed in cluster mode')
# self.db = ''
# await super(ClusterConnection, self).on_connect()
# if self.readonly:
# await self.send_command('READONLY')
# if nativestr(await self.read_response()) != 'OK':
# raise ConnectionError('READONLY command failed')
#
# Path: aredis/exceptions.py
# class LockError(RedisError, ValueError):
# """Errors acquiring or releasing a lock"""
# # NOTE: For backwards compatability, this class derives from ValueError.
# # This was originally chosen to behave like threading.Lock.
# pass
#
# class WatchError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# class dummy:
# """
# Instances of this class can be used as an attribute container.
# """
#
# def __init__(self):
# self.token = None
#
# def set(self, value):
# self.token = value
#
# def get(self):
# return self.token
. Output only the next line. | 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 dummy()
if self.timeout and self.sleep > self.timeout:
raise LockError("'sleep' must be less than 'timeout'")
async def __aenter__(self):
# force blocking, as otherwise the user would have to check whether
# the lock was actually acquired or not.
await self.acquire(blocking=True)
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await self.release()
async def acquire(self, blocking=None, blocking_timeout=None):
"""
Use Redis to hold a shared, distributed lock named ``name``.
Returns True once the lock is acquired.
If ``blocking`` is False, always return immediately. If the lock
was acquired, return True, otherwise return False.
``blocking_timeout`` specifies the maximum number of seconds to
wait trying to acquire the lock.
"""
sleep = self.sleep
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import time as mod_time
import uuid
import warnings
import contextvars
from aredis.connection import ClusterConnection
from aredis.exceptions import LockError, WatchError
from aredis.utils import b, dummy
and context (classes, functions, sometimes code) from other files:
# Path: aredis/connection.py
# class ClusterConnection(Connection):
# "Manages TCP communication to and from a Redis server"
# description = "ClusterConnection<host={host},port={port}>"
#
# def __init__(self, *args, **kwargs):
# self.readonly = kwargs.pop('readonly', False)
# super(ClusterConnection, self).__init__(*args, **kwargs)
#
# async def on_connect(self):
# """
# Initialize the connection, authenticate and select a database and send READONLY if it is
# set during object initialization.
# """
# if self.db:
# warnings.warn('SELECT DB is not allowed in cluster mode')
# self.db = ''
# await super(ClusterConnection, self).on_connect()
# if self.readonly:
# await self.send_command('READONLY')
# if nativestr(await self.read_response()) != 'OK':
# raise ConnectionError('READONLY command failed')
#
# Path: aredis/exceptions.py
# class LockError(RedisError, ValueError):
# """Errors acquiring or releasing a lock"""
# # NOTE: For backwards compatability, this class derives from ValueError.
# # This was originally chosen to behave like threading.Lock.
# pass
#
# class WatchError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# class dummy:
# """
# Instances of this class can be used as an attribute container.
# """
#
# def __init__(self):
# self.token = None
#
# def set(self, value):
# self.token = value
#
# def get(self):
# return self.token
. Output only the next line. | 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
Lock instance.
time: 5, thread-1 has not yet completed. redis expires the lock
key.
time: 5, thread-2 acquired `my-lock` now that it's available.
thread-2 sets the token to "xyz"
time: 6, thread-1 finishes its work and calls release(). if the
token is *not* stored in thread local storage, then
thread-1 would see the token value as "xyz" and would be
able to successfully release the thread-2's lock.
In some use cases it's necessary to disable thread local storage. For
example, if you have code where one thread acquires a lock and passes
that lock instance to a worker thread to release later. If thread
local storage isn't disabled in this case, the worker thread won't see
the token set by the thread that acquired the lock. Our assumption
is that these cases aren't common and as such default to using
thread local storage.
"""
self.redis = redis
self.name = name
self.timeout = timeout
self.sleep = sleep
self.blocking = blocking
self.blocking_timeout = blocking_timeout
self.thread_local = bool(thread_local)
<|code_end|>
with the help of current file imports:
import asyncio
import time as mod_time
import uuid
import warnings
import contextvars
from aredis.connection import ClusterConnection
from aredis.exceptions import LockError, WatchError
from aredis.utils import b, dummy
and context from other files:
# Path: aredis/connection.py
# class ClusterConnection(Connection):
# "Manages TCP communication to and from a Redis server"
# description = "ClusterConnection<host={host},port={port}>"
#
# def __init__(self, *args, **kwargs):
# self.readonly = kwargs.pop('readonly', False)
# super(ClusterConnection, self).__init__(*args, **kwargs)
#
# async def on_connect(self):
# """
# Initialize the connection, authenticate and select a database and send READONLY if it is
# set during object initialization.
# """
# if self.db:
# warnings.warn('SELECT DB is not allowed in cluster mode')
# self.db = ''
# await super(ClusterConnection, self).on_connect()
# if self.readonly:
# await self.send_command('READONLY')
# if nativestr(await self.read_response()) != 'OK':
# raise ConnectionError('READONLY command failed')
#
# Path: aredis/exceptions.py
# class LockError(RedisError, ValueError):
# """Errors acquiring or releasing a lock"""
# # NOTE: For backwards compatability, this class derives from ValueError.
# # This was originally chosen to behave like threading.Lock.
# pass
#
# class WatchError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# class dummy:
# """
# Instances of this class can be used as an attribute container.
# """
#
# def __init__(self):
# self.token = None
#
# def set(self, value):
# self.token = value
#
# def get(self):
# return self.token
, which may contain function names, class names, or code. Output only the next line. | 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.set('a', 2)
# 2 * 3 == 6
assert await r.eval(multiply_script, 1, 'a', 3) == 6
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_evalsha(self, r):
await r.set('a', 2)
sha = await r.script_load(multiply_script)
# 2 * 3 == 6
assert await r.evalsha(sha, 1, 'a', 3) == 6
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_evalsha_script_not_loaded(self, r):
await r.set('a', 2)
sha = await r.script_load(multiply_script)
# remove the script from Redis's cache
await r.script_flush()
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from aredis.exceptions import (NoScriptError,
ResponseError)
from aredis.utils import b
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class NoScriptError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
. Output only the next line. | 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', result of multiple script]
assert await pipe.execute() == [True, b('2'), 6]
assert await r.script_exists(multiply.sha) == [True]
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_eval_msgpack_pipeline_error_in_lua(self, r):
msgpack_hello = r.register_script(msgpack_hello_script)
assert msgpack_hello.sha
pipe = await r.pipeline()
# avoiding a dependency to msgpack, this is the output of
# msgpack.dumps({"name": "joe"})
msgpack_message_1 = b'\x81\xa4name\xa3Joe'
await msgpack_hello.execute(args=[msgpack_message_1], client=pipe)
assert await r.script_exists(msgpack_hello.sha) == [False]
assert (await pipe.execute())[0] == b'hello Joe'
assert await r.script_exists(msgpack_hello.sha) == [True]
msgpack_hello_broken = r.register_script(msgpack_hello_script_broken)
await msgpack_hello_broken.execute(args=[msgpack_message_1], client=pipe)
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from aredis.exceptions import (NoScriptError,
ResponseError)
from aredis.utils import b
and context (classes, functions, sometimes code) from other files:
# Path: aredis/exceptions.py
# class NoScriptError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
. Output only the next line. | 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 r.script_exists(multiply.sha) == [False]
# Test second evalsha block (after NoScriptError)
assert await multiply.execute(keys=['a'], args=[3]) == 6
# At this point, the script should be loaded
assert await r.script_exists(multiply.sha) == [True]
# Test that the precalculated sha matches the one from redis
assert multiply.sha == precalculated_sha
# Test first evalsha block
assert await multiply.execute(keys=['a'], args=[3]) == 6
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_script_object_in_pipeline(self, r):
await r.script_flush()
multiply = r.register_script(multiply_script)
precalculated_sha = multiply.sha
assert precalculated_sha
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', result of multiple script]
<|code_end|>
. Use current file imports:
(import pytest
from aredis.exceptions import (NoScriptError,
ResponseError)
from aredis.utils import b)
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class NoScriptError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
. Output only the next line. | 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 ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCORE',
zset_score_pairs
),
string_keys_to_dict('ZRANK ZREVRANK', int_or_none),
{
'ZSCAN': parse_zscan,
}
)
async def zadd(self, name, *args, **kwargs):
"""
Set any number of score, element-name pairs to the key ``name``. Pairs
can be specified in two ways:
As *args, in the form of: score1, name1, score2, name2, ...
or as **kwargs, in the form of: name1=score1, name2=score2, ...
The following example would add four values to the 'my-key' key:
redis.zadd('my-key', 1.1, 'name1', 2.2, 'name2', name3=3.3, name4=4.4)
"""
pieces = []
if args:
if len(args) % 2 != 0:
<|code_end|>
with the help of current file imports:
import re
from aredis.exceptions import RedisError
from aredis.utils import (b, iteritems,
first_key,
iterkeys,
itervalues,
dict_merge,
string_keys_to_dict,
int_or_none)
and context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
, which may contain function names, class names, or code. Output only the next line. | 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``.
"""
return await self.execute_command('ZLEXCOUNT', name, min, max)
async def zrange(self, name, start, end, desc=False, withscores=False,
score_cast_func=float):
"""
Returns a range of values from sorted set ``name`` between
``start`` and ``end`` sorted in ascending order.
``start`` and ``end`` can be negative, indicating the end of the range.
``desc`` a boolean indicating whether to sort the results descendingly
``withscores`` indicates to return the scores along with the values.
The return type is a list of (value, score) pairs
``score_cast_func`` a callable used to cast the score return value
"""
if desc:
return await self.zrevrange(name, start, end, withscores,
score_cast_func)
pieces = ['ZRANGE', name, start, end]
if withscores:
<|code_end|>
. Use current file imports:
import re
from aredis.exceptions import RedisError
from aredis.utils import (b, iteritems,
first_key,
iterkeys,
itervalues,
dict_merge,
string_keys_to_dict,
int_or_none)
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
. Output only the next line. | 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', int_or_none),
{
'ZSCAN': parse_zscan,
}
)
async def zadd(self, name, *args, **kwargs):
"""
Set any number of score, element-name pairs to the key ``name``. Pairs
can be specified in two ways:
As *args, in the form of: score1, name1, score2, name2, ...
or as **kwargs, in the form of: name1=score1, name2=score2, ...
The following example would add four values to the 'my-key' key:
redis.zadd('my-key', 1.1, 'name1', 2.2, 'name2', name3=3.3, name4=4.4)
"""
pieces = []
if args:
if len(args) % 2 != 0:
raise RedisError("ZADD requires an equal number of "
"values and scores")
pieces.extend(args)
<|code_end|>
. Write the next line using the current file imports:
import re
from aredis.exceptions import RedisError
from aredis.utils import (b, iteritems,
first_key,
iterkeys,
itervalues,
dict_merge,
string_keys_to_dict,
int_or_none)
and context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
, which may include functions, classes, or code. Output only the next line. | 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_func=float):
"""
Incrementally returns lists of elements in a sorted set. Also returns
a cursor pointing to the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
``score_cast_func`` a callable used to cast the score return value
"""
pieces = [name, cursor]
if match is not None:
pieces.extend([b('MATCH'), match])
if count is not None:
pieces.extend([b('COUNT'), count])
options = {'score_cast_func': score_cast_func}
return await self.execute_command('ZSCAN', *pieces, **options)
class ClusterSortedSetCommandMixin(SortedSetCommandMixin):
RESULT_CALLBACKS = {
<|code_end|>
, determine the next line of code. You have imports:
import re
from aredis.exceptions import RedisError
from aredis.utils import (b, iteritems,
first_key,
iterkeys,
itervalues,
dict_merge,
string_keys_to_dict,
int_or_none)
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
. Output only the next line. | '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, value):
"""
Returns a 0-based value indicating the descending rank of
``value`` in sorted set ``name``
"""
return await self.execute_command('ZREVRANK', name, value)
async def zscore(self, name, value):
"Return the score of element ``value`` in sorted set ``name``"
return await self.execute_command('ZSCORE', name, value)
async def zunionstore(self, dest, keys, aggregate=None):
"""
Performs Union on multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided.
"""
return await self._zaggregate('ZUNIONSTORE', dest, keys, aggregate)
async def _zaggregate(self, command, dest, keys, aggregate=None):
pieces = [command, dest, len(keys)]
if isinstance(keys, dict):
<|code_end|>
. Use current file imports:
import re
from aredis.exceptions import RedisError
from aredis.utils import (b, iteritems,
first_key,
iterkeys,
itervalues,
dict_merge,
string_keys_to_dict,
int_or_none)
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
. Output only the next line. | 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 zrevrank(self, name, value):
"""
Returns a 0-based value indicating the descending rank of
``value`` in sorted set ``name``
"""
return await self.execute_command('ZREVRANK', name, value)
async def zscore(self, name, value):
"Return the score of element ``value`` in sorted set ``name``"
return await self.execute_command('ZSCORE', name, value)
async def zunionstore(self, dest, keys, aggregate=None):
"""
Performs Union on multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided.
"""
return await self._zaggregate('ZUNIONSTORE', dest, keys, aggregate)
async def _zaggregate(self, command, dest, keys, aggregate=None):
pieces = [command, dest, len(keys)]
if isinstance(keys, dict):
<|code_end|>
using the current file's imports:
import re
from aredis.exceptions import RedisError
from aredis.utils import (b, iteritems,
first_key,
iterkeys,
itervalues,
dict_merge,
string_keys_to_dict,
int_or_none)
and any relevant context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
. Output only the next line. | 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 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, **options):
score_cast_func = options.get('score_cast_func', float)
cursor, r = response
it = iter(r)
return int(cursor), list(zip(it, map(score_cast_func, it)))
class SortedSetCommandMixin:
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from aredis.exceptions import RedisError
from aredis.utils import (b, iteritems,
first_key,
iterkeys,
itervalues,
dict_merge,
string_keys_to_dict,
int_or_none)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
. Output only the next line. | 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 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, **options):
score_cast_func = options.get('score_cast_func', float)
cursor, r = response
it = iter(r)
return int(cursor), list(zip(it, map(score_cast_func, it)))
class SortedSetCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
<|code_end|>
, determine the next line of code. You have imports:
import re
from aredis.exceptions import RedisError
from aredis.utils import (b, iteritems,
first_key,
iterkeys,
itervalues,
dict_merge,
string_keys_to_dict,
int_or_none)
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
. Output only the next line. | 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, **options):
score_cast_func = options.get('score_cast_func', float)
cursor, r = response
it = iter(r)
return int(cursor), list(zip(it, map(score_cast_func, it)))
class SortedSetCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'ZADD ZCARD ZLEXCOUNT '
'ZREM ZREMRANGEBYLEX '
'ZREMRANGEBYRANK '
'ZREMRANGEBYSCORE', int
),
string_keys_to_dict('ZSCORE ZINCRBY', float_or_none),
string_keys_to_dict(
'ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCORE',
zset_score_pairs
),
<|code_end|>
. Use current file imports:
(import re
from aredis.exceptions import RedisError
from aredis.utils import (b, iteritems,
first_key,
iterkeys,
itervalues,
dict_merge,
string_keys_to_dict,
int_or_none))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
. Output only the next line. | 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])
return value * value2
"""
result = await r.eval(script, 2, 'A{foo}', 'B{foo}')
assert result == 8
@pytest.mark.asyncio()
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)
# 2 * 4 == 8
script = """
local value = redis.call('GET', KEYS[1])
local value2 = redis.call('GET', KEYS[2])
return value * value2
"""
<|code_end|>
. Use current file imports:
(import asyncio
import pytest
from aredis.exceptions import RedisClusterException, NoScriptError, ResponseError
from aredis.utils import b)
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
. Output only the next line. | 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)
# 2 * 4 == 8
script = """
local value = redis.call('GET', KEYS[1])
local value2 = redis.call('GET', KEYS[2])
return value * value2
"""
with pytest.raises(RedisClusterException):
await r.eval(script, 2, 'A{foo}', 'B{bar}')
@pytest.mark.asyncio()
async def test_evalsha(self, r):
await r.set('a', 2)
sha = await r.script_load(multiply_script)
# 2 * 3 == 6
assert await r.evalsha(sha, 1, 'a', 3) == 6
@pytest.mark.asyncio()
async def test_evalsha_script_not_loaded(self, r):
await r.set('a', 2)
sha = await r.script_load(multiply_script)
# remove the script from Redis's cache
await r.script_flush()
<|code_end|>
. Use current file imports:
(import asyncio
import pytest
from aredis.exceptions import RedisClusterException, NoScriptError, ResponseError
from aredis.utils import b)
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
. Output only the next line. | 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, GET 'a', result of multiple script]
assert await pipe.execute() == [True, b('2'), 6]
@pytest.mark.asyncio(forbid_global_loop=True)
@pytest.mark.xfail(reason="Not Yet Implemented")
async def test_eval_msgpack_pipeline_error_in_lua(self, r):
msgpack_hello = await r.register_script(msgpack_hello_script)
assert not msgpack_hello.sha
pipe = r.pipeline()
# avoiding a dependency to msgpack, this is the output of
# msgpack.dumps({"name": "joe"})
msgpack_message_1 = b'\x81\xa4name\xa3Joe'
msgpack_hello(args=[msgpack_message_1], client=pipe)
assert await r.script_exists(msgpack_hello.sha) == [True]
assert await pipe.execute()[0] == b'hello Joe'
msgpack_hello_broken = await r.register_script(msgpack_hello_script_broken)
msgpack_hello_broken(args=[msgpack_message_1], client=pipe)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import pytest
from aredis.exceptions import RedisClusterException, NoScriptError, ResponseError
from aredis.utils import b
and context:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
which might include code, classes, or functions. Output only the next line. | 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_script(multiply_script)
assert multiply.sha == '29cdf3e36c89fa05d7e6d6b9734b342ab15c9ea7'
# test evalsha fail -> script load + retry
assert await multiply.execute(keys=['a'], args=[3]) == 6
assert multiply.sha
assert await r.script_exists(multiply.sha) == [True]
# test first evalsha
assert await multiply.execute(keys=['a'], args=[3]) == 6
@pytest.mark.asyncio(forbid_global_loop=True)
@pytest.mark.xfail(reason="Not Yet Implemented")
async def test_script_object_in_pipeline(self, r):
multiply = await r.register_script(multiply_script)
assert not multiply.sha
pipe = r.pipeline()
await pipe.set('a', 2)
await pipe.get('a')
multiply(keys=['a'], args=[3], client=pipe)
# even though the pipeline wasn't executed yet, we made sure the
# script was loaded and got a valid sha
assert multiply.sha
assert await r.script_exists(multiply.sha) == [True]
# [SET worked, GET 'a', result of multiple script]
<|code_end|>
. Use current file imports:
(import asyncio
import pytest
from aredis.exceptions import RedisClusterException, NoScriptError, ResponseError
from aredis.utils import b)
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
. Output only the next line. | 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):
"""Returns the union of sets specified by ``keys``"""
args = list_or_args(keys, args)
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.
"""
args = list_or_args(keys, args)
return await self.execute_command('SUNIONSTORE', dest, *args)
async def sscan(self, name, cursor=0, match=None, count=None):
"""
Incrementally returns lists of elements in a set. Also returns a
cursor pointing to the scan position.
``match`` is for filtering the keys by pattern
``count`` is for hint the minimum number of returns
"""
pieces = [name, cursor]
if match is not None:
<|code_end|>
. Use current file imports:
(from aredis.utils import (b, dict_merge,
list_or_args,
first_key,
string_keys_to_dict))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | 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,
first_key,
string_keys_to_dict)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | 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
),
string_keys_to_dict(
'SDIFF SINTER SMEMBERS SUNION',
lambda r: r and set(r) or set()
),
{
'SSCAN': parse_sscan,
}
)
async def sadd(self, name, *values):
"""Adds ``value(s)`` to set ``name``"""
return await self.execute_command('SADD', name, *values)
async def scard(self, name):
"""Returns the number of elements in set ``name``"""
return await self.execute_command('SCARD', name)
async def sdiff(self, keys, *args):
"""Returns the difference of sets specified by ``keys``"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from aredis.utils import (b, dict_merge,
list_or_args,
first_key,
string_keys_to_dict)
and context:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
which might include code, classes, or functions. Output only the next line. | 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.
"""
args = list_or_args(keys, args)
return await self.execute_command('SUNIONSTORE', dest, *args)
async def sscan(self, name, cursor=0, match=None, count=None):
"""
Incrementally returns lists of elements in a set. Also returns a
cursor pointing to the scan position.
``match`` is for filtering the keys by pattern
``count`` is for hint the minimum number of returns
"""
pieces = [name, cursor]
if match is not None:
pieces.extend([b('MATCH'), match])
if count is not None:
pieces.extend([b('COUNT'), count])
return await self.execute_command('SSCAN', *pieces)
class ClusterSetsCommandMixin(SetsCommandMixin):
RESULT_CALLBACKS = {
<|code_end|>
using the current file's imports:
from aredis.utils import (b, dict_merge,
list_or_args,
first_key,
string_keys_to_dict)
and any relevant context from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | '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,
first_key,
string_keys_to_dict))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
. Output only the next line. | 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 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"""
# NOTE: don't parse the response in this function -- it could pull a
# legitimate message off the stack if the connection is already
# subscribed to one or more channels
if self.connection is None:
self.connection = self.connection_pool.get_connection()
# register a callback that re-subscribes to any channels we
# were listening to when we were disconnected
self.connection.register_connect_callback(self.on_connect)
connection = self.connection
await self._execute(connection, connection.send_command, *args)
async def _execute(self, connection, command, *args):
try:
return await command(*args)
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import threading
from aredis.compat import CancelledError
from aredis.exceptions import PubSubError, ConnectionError, TimeoutError
from aredis.utils import (list_or_args,
iteritems,
iterkeys,
nativestr)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/compat.py
#
# Path: aredis/exceptions.py
# class PubSubError(RedisError):
# pass
#
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# Path: aredis/utils.py
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | 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:
pass
if message_type in self.PUBLISH_MESSAGE_TYPES:
# if there's a message handler, invoke it
handler = None
if message_type == 'pmessage':
handler = self.patterns.get(message['pattern'], None)
else:
handler = self.channels.get(message['channel'], None)
if handler:
handler(message)
return None
else:
# this is a subscribe/unsubscribe message. ignore if we don't
# want them
if ignore_subscribe_messages or self.ignore_subscribe_messages:
return None
return message
def run_in_thread(self, daemon=False, poll_timeout=1.0):
for channel, handler in iteritems(self.channels):
if handler is None:
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import threading
from aredis.compat import CancelledError
from aredis.exceptions import PubSubError, ConnectionError, TimeoutError
from aredis.utils import (list_or_args,
iteritems,
iterkeys,
nativestr)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/compat.py
#
# Path: aredis/exceptions.py
# class PubSubError(RedisError):
# pass
#
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# Path: aredis/utils.py
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | 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"""
# NOTE: don't parse the response in this function -- it could pull a
# legitimate message off the stack if the connection is already
# subscribed to one or more channels
if self.connection is None:
self.connection = self.connection_pool.get_connection()
# register a callback that re-subscribes to any channels we
# were listening to when we were disconnected
self.connection.register_connect_callback(self.on_connect)
connection = self.connection
await self._execute(connection, connection.send_command, *args)
async def _execute(self, connection, command, *args):
try:
return await command(*args)
except CancelledError:
# do not retry if coroutine is cancelled
if await connection.can_read():
# disconnect if buffer is not empty in case of error
# when connection is reused
connection.disconnect()
return None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import threading
from aredis.compat import CancelledError
from aredis.exceptions import PubSubError, ConnectionError, TimeoutError
from aredis.utils import (list_or_args,
iteritems,
iterkeys,
nativestr)
and context:
# Path: aredis/compat.py
#
# Path: aredis/exceptions.py
# class PubSubError(RedisError):
# pass
#
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# Path: aredis/utils.py
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
which might include code, classes, or functions. Output only the next line. | 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"""
# NOTE: don't parse the response in this function -- it could pull a
# legitimate message off the stack if the connection is already
# subscribed to one or more channels
if self.connection is None:
self.connection = self.connection_pool.get_connection()
# register a callback that re-subscribes to any channels we
# were listening to when we were disconnected
self.connection.register_connect_callback(self.on_connect)
connection = self.connection
await self._execute(connection, connection.send_command, *args)
async def _execute(self, connection, command, *args):
try:
return await command(*args)
except CancelledError:
# do not retry if coroutine is cancelled
if await connection.can_read():
# disconnect if buffer is not empty in case of error
# when connection is reused
connection.disconnect()
return None
<|code_end|>
. Use current file imports:
import asyncio
import threading
from aredis.compat import CancelledError
from aredis.exceptions import PubSubError, ConnectionError, TimeoutError
from aredis.utils import (list_or_args,
iteritems,
iterkeys,
nativestr)
and context (classes, functions, or code) from other files:
# Path: aredis/compat.py
#
# Path: aredis/exceptions.py
# class PubSubError(RedisError):
# pass
#
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# Path: aredis/utils.py
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | 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 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: '
'did you forget to call subscribe() or psubscribe()?')
coro = self._execute(connection, connection.read_response)
if not block and timeout > 0:
try:
return await asyncio.wait_for(coro, timeout)
except Exception:
return None
return await coro
async def psubscribe(self, *args, **kwargs):
"""
Subscribes to channel patterns. Patterns supplied as keyword arguments
expect a pattern name as the key and a callable as the value. A
pattern's callable will be invoked automatically when a message is
received on that pattern rather than producing a message via
``listen()``.
"""
if args:
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import threading
from aredis.compat import CancelledError
from aredis.exceptions import PubSubError, ConnectionError, TimeoutError
from aredis.utils import (list_or_args,
iteritems,
iterkeys,
nativestr)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/compat.py
#
# Path: aredis/exceptions.py
# class PubSubError(RedisError):
# pass
#
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# Path: aredis/utils.py
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | 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 Exception:
pass
def reset(self):
if self.connection:
self.connection.disconnect()
self.connection.clear_connect_callbacks()
self.connection_pool.release(self.connection)
self.connection = None
self.channels = {}
self.patterns = {}
def close(self):
self.reset()
async def on_connect(self, connection):
"""Re-subscribe to any channels and patterns previously subscribed to"""
# NOTE: for python3, we can't pass bytestrings as keyword arguments
# so we need to decode channel/pattern names back to str strings
# before passing them to [p]subscribe.
if self.channels:
channels = {}
<|code_end|>
. Write the next line using the current file imports:
import asyncio
import threading
from aredis.compat import CancelledError
from aredis.exceptions import PubSubError, ConnectionError, TimeoutError
from aredis.utils import (list_or_args,
iteritems,
iterkeys,
nativestr)
and context from other files:
# Path: aredis/compat.py
#
# Path: aredis/exceptions.py
# class PubSubError(RedisError):
# pass
#
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# Path: aredis/utils.py
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
, which may include functions, classes, or code. Output only the next line. | 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: '
'did you forget to call subscribe() or psubscribe()?')
coro = self._execute(connection, connection.read_response)
if not block and timeout > 0:
try:
return await asyncio.wait_for(coro, timeout)
except Exception:
return None
return await coro
async def psubscribe(self, *args, **kwargs):
"""
Subscribes to channel patterns. Patterns supplied as keyword arguments
expect a pattern name as the key and a callable as the value. A
pattern's callable will be invoked automatically when a message is
received on that pattern rather than producing a message via
``listen()``.
"""
if args:
args = list_or_args(args[0], args[1:])
new_patterns = {}
new_patterns.update(dict.fromkeys(map(self.encode, args)))
for pattern, handler in iteritems(kwargs):
new_patterns[self.encode(pattern)] = handler
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import threading
from aredis.compat import CancelledError
from aredis.exceptions import PubSubError, ConnectionError, TimeoutError
from aredis.utils import (list_or_args,
iteritems,
iterkeys,
nativestr)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/compat.py
#
# Path: aredis/exceptions.py
# class PubSubError(RedisError):
# pass
#
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# Path: aredis/utils.py
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | 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:
return self.handle_message(await self.parse_response(block=True))
async def get_message(self, ignore_subscribe_messages=False, timeout=0):
"""
Gets the next message if one is available, otherwise None.
If timeout is specified, the system will wait for `timeout` seconds
before returning. Timeout should be specified as a floating point
number.
"""
response = await self.parse_response(block=False, timeout=timeout)
if response:
return self.handle_message(response, ignore_subscribe_messages)
return None
def handle_message(self, response, ignore_subscribe_messages=False):
"""
Parses a pub/sub message. If the channel or pattern was subscribed to
with a message handler, the handler is invoked instead of a parsed
message being returned.
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import threading
from aredis.compat import CancelledError
from aredis.exceptions import PubSubError, ConnectionError, TimeoutError
from aredis.utils import (list_or_args,
iteritems,
iterkeys,
nativestr)
and context:
# Path: aredis/compat.py
#
# Path: aredis/exceptions.py
# class PubSubError(RedisError):
# pass
#
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# Path: aredis/utils.py
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
which might include code, classes, or functions. Output only the next line. | 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')
await pipe.zadd('z', z1=1)
await pipe.zadd('z', z2=4)
await pipe.zincrby('z', 'z1')
await pipe.zrange('z', 0, 5, withscores=True)
assert await pipe.execute() == \
[
True,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from aredis.utils import b
from aredis.exceptions import (WatchError,
ResponseError)
and context:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# Path: aredis/exceptions.py
# class WatchError(RedisError):
# pass
#
# class ResponseError(RedisError):
# pass
which might include code, classes, or functions. Output only the next line. | 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.pipeline(transaction=False) as pipe:
await pipe.watch('a')
a = await pipe.get('a')
pipe.multi()
await pipe.set('a', int(a) + 1)
assert await pipe.execute() == [True]
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_pipeline_no_transaction_watch_failure(self, r):
await r.flushdb()
await r.set('a', 0)
async with await r.pipeline(transaction=False) as pipe:
await pipe.watch('a')
a = await pipe.get('a')
await r.set('a', 'bad')
pipe.multi()
await pipe.set('a', int(a) + 1)
<|code_end|>
. Write the next line using the current file imports:
import pytest
from aredis.utils import b
from aredis.exceptions import (WatchError,
ResponseError)
and context from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# Path: aredis/exceptions.py
# class WatchError(RedisError):
# pass
#
# class ResponseError(RedisError):
# pass
, which may include functions, classes, or code. Output only the next line. | 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 test_exec_error_in_response(self, r):
"""
an invalid pipeline command at exec time adds the exception instance
to the list of returned values
"""
await r.flushdb()
await r.set('c', 'a')
async with await r.pipeline() as pipe:
await pipe.set('a', 1)
await pipe.set('b', 2)
await pipe.lpush('c', 3)
await pipe.set('d', 4)
result = await pipe.execute(raise_on_error=False)
assert result[0]
assert await r.get('a') == b('1')
assert result[1]
assert await r.get('b') == b('2')
# we can't lpush to a key that's a string value, so this should
# be a ResponseError exception
<|code_end|>
with the help of current file imports:
import pytest
from aredis.utils import b
from aredis.exceptions import (WatchError,
ResponseError)
and context from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# Path: aredis/exceptions.py
# class WatchError(RedisError):
# pass
#
# class ResponseError(RedisError):
# pass
, which may contain function names, class names, or code. Output only the next line. | 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.mark.asyncio(forbid_global_loop=True)
async def test_echo(self, r):
assert await r.echo('foo bar') == b'foo bar'
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_info(self, r):
await r.set('a', 'foo')
await r.set('b', 'bar')
info = await r.info()
assert isinstance(info, dict)
assert info['db0']['keys'] == 2
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_lastsave(self, r):
assert isinstance(await r.lastsave(), datetime.datetime)
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_object(self, r):
await r.set('a', 'foo')
assert isinstance(await r.object('refcount', 'a'), int)
assert isinstance(await r.object('idletime', 'a'), int)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and context:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
which might include code, classes, or functions. Output only the next line. | 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 test_keys(self, r):
await r.flushdb()
assert await r.keys() == []
keys_with_underscores = {b('test_a'), b('test_b')}
keys = keys_with_underscores.union({b('testc')})
for key in keys:
await r.set(key, 1)
assert set(await r.keys(pattern='test_*')) == keys_with_underscores
assert set(await r.keys(pattern='test*')) == keys
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_mget(self, r):
await r.flushdb()
assert await r.mget(['a', 'b']) == [None, None]
await r.set('a', '1')
await r.set('b', '2')
await r.set('c', '3')
assert await r.mget('a', 'other', 'b', 'c') == [b('1'), None, b('2'), b('3')]
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_mset(self, r):
d = {'a': b('1'), 'b': b('2'), 'c': b('3')}
assert await r.mset(d)
<|code_end|>
, predict the immediate next line with the help of imports:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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', h)
assert await r.hgetall('a') == h
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_hincrby(self, r):
await r.flushdb()
assert await r.hincrby('a', '1') == 1
assert await r.hincrby('a', '1', amount=2) == 3
assert await r.hincrby('a', '1', amount=-2) == 1
@skip_if_server_version_lt('2.6.0')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_hincrbyfloat(self, r):
await r.flushdb()
assert await r.hincrbyfloat('a', '1') == 1.0
assert await r.hincrbyfloat('a', '1') == 2.0
assert await r.hincrbyfloat('a', '1', 1.2) == 3.2
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_hkeys(self, r):
await r.flushdb()
h = {b('a1'): b('1'), b('a2'): b('2'), b('a3'): b('3')}
await r.hmset('a', h)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and context:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
which might include code, classes, or functions. Output only the next line. | 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})
assert await r.hmget('a', 'a', 'b', 'c') == [b('1'), b('2'), b('3')]
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_hmset(self, r):
await r.flushdb()
h = {b('a'): b('1'), b('b'): b('2'), b('c'): b('3')}
assert await r.hmset('a', h)
assert await r.hgetall('a') == h
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_hsetnx(self, r):
await r.flushdb()
# Initially set the hash field
assert await r.hsetnx('a', '1', 1)
assert await r.hget('a', '1') == b('1')
assert not await r.hsetnx('a', '1', 2)
assert await r.hget('a', '1') == b('1')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_hvals(self, r):
await r.flushdb()
h = {b('a1'): b('1'), b('a2'): b('2'), b('a3'): b('3')}
await r.hmset('a', h)
<|code_end|>
using the current file's imports:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and any relevant context from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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," \
b"13=123,14=3091,15=11048,16=225842,17=1784,18=814,19=12020," \
b"20=2530,21=645,22=15113,23=8695,24=142860,25=318,26=3303," \
b"27=20561,28=54042,29=37390,30=1884,31=18071,32=31367,33=160," \
b"34=169,35=201,36=10155,37=1045,38=15078,39=22985,40=12523," \
b"41=15588,42=265,43=1287,44=142,45=382,46=945,47=426,48=171," \
b"49=56,50=516,51=43,52=41,53=46,54=54,55=75,56=647,57=332," \
b"58=32,59=39,60=48,61=35,62=62,63=32,64=221,65=26,66=30," \
b"67=36,68=41,69=44,70=26,71=144,72=169,73=24,74=37,75=25," \
b"76=42,77=21,78=126,79=374,80=27,81=40,82=43,83=47,84=46," \
b"85=114,86=34,87=37,88=7240,89=34,90=38,91=18,92=99,93=20," \
b"94=18,95=17,96=15,97=22,98=18,99=69,100=17,101=22,102=15," \
b"103=29,104=39,105=30,106=70,107=22,108=21,109=26,110=52," \
b"111=45,112=33,113=67,114=41,115=44,116=48,117=53,118=54," \
b"119=51,120=75,121=44,122=57,123=44,124=66,125=56,126=52," \
b"127=81,128=108,129=70,130=50,131=51,132=53,133=45,134=62," \
b"135=12,136=13,137=7,138=15,139=21,140=11,141=20,142=6,143=7," \
b"144=11,145=6,146=16,147=19,148=1112,149=1,151=83,154=1," \
b"155=1,156=1,157=1,160=1,161=1,162=2,166=1,169=1,170=1,171=2," \
b"172=1,174=1,176=2,177=9,178=34,179=73,180=30,181=1,185=3," \
b"187=1,188=1,189=1,192=1,196=1,198=1,200=1,201=1,204=1,205=1," \
b"207=1,208=1,209=1,214=2,215=31,216=78,217=28,218=5,219=2," \
b"220=1,222=1,225=1,227=1,234=1,242=1,250=1,252=1,253=1," \
b">=256=203"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and context:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
which might include code, classes, or functions. Output only the next line. | 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', 'b')
await r.bitop('xor', 'res3', 'a', 'b')
assert int(binascii.hexlify(await r.get('res1')), 16) == 0x0102FF00
assert int(binascii.hexlify(await r.get('res2')), 16) == 0x0102FFFF
assert int(binascii.hexlify(await r.get('res3')), 16) == 0x000000FF
@skip_if_server_version_lt('2.8.7')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_bitpos(self, r):
key = 'key:bitpos'
await r.set(key, b('\xff\xf0\x00'))
assert await r.bitpos(key, 0) == 12
assert await r.bitpos(key, 0, 2, -1) == 16
assert await r.bitpos(key, 0, -2, -1) == 12
await r.set(key, b('\x00\xff\xf0'))
assert await r.bitpos(key, 1, 0) == 8
assert await r.bitpos(key, 1, 1) == 8
await r.set(key, b('\x00\x00\x00'))
assert await r.bitpos(key, 1) == -1
@skip_if_server_version_lt('2.8.7')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_bitpos_wrong_arguments(self, r):
key = 'key:bitpos:wrong:args'
await r.set(key, b('\xff\xf0\x00'))
<|code_end|>
. Use current file imports:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and context (classes, functions, or code) from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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 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
assert id(r.response_callbacks) != id(aredis.StrictRedis.RESPONSE_CALLBACKS)
r.set_response_callback('GET', lambda x: 'static')
await r.set('a', 'foo')
assert await r.get('a') == 'static'
class TestRedisCommands:
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_command_on_invalid_key_type(self, r):
await r.flushdb()
await r.lpush('a', '1')
<|code_end|>
, predict the immediate next line with the help of imports:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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')
await r.set('user:2', 'u2')
await r.set('user:3', 'u3')
await r.rpush('a', '2', '3', '1')
assert await r.sort('a', get=('user:*', '#')) == \
[b('u1'), b('1'), b('u2'), b('2'), b('u3'), b('3')]
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_sort_get_groups_two(self, r):
await r.flushdb()
await r.set('user:1', 'u1')
await r.set('user:2', 'u2')
await r.set('user:3', 'u3')
await r.rpush('a', '2', '3', '1')
assert await r.sort('a', get=('user:*', '#'), groups=True) == \
[(b('u1'), b('1')), (b('u2'), b('2')), (b('u3'), b('3'))]
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_sort_groups_string_get(self, r):
await r.flushdb()
await r.set('user:1', 'u1')
await r.set('user:2', 'u2')
await r.set('user:3', 'u3')
await r.rpush('a', '2', '3', '1')
<|code_end|>
, determine the next line of code. You have imports:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and context (class names, function names, or code) available:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | 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
assert id(r.response_callbacks) != id(aredis.StrictRedis.RESPONSE_CALLBACKS)
r.set_response_callback('GET', lambda x: 'static')
await r.set('a', 'foo')
assert await r.get('a') == 'static'
class TestRedisCommands:
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_command_on_invalid_key_type(self, r):
await r.flushdb()
await r.lpush('a', '1')
with pytest.raises(ResponseError):
await r.get('a')
# SERVER INFORMATION
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_client_list(self, r):
clients = await r.client_list()
assert isinstance(clients[0], dict)
assert 'addr' in clients[0]
<|code_end|>
, generate the next line using the imports in this file:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | @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=True)
async def test_rpushx(self, r):
await r.flushdb()
assert await r.rpushx('a', 'b') == 0
assert await r.lrange('a', 0, -1) == []
await r.rpush('a', '1', '2', '3')
assert await r.rpushx('a', '4') == 4
assert await r.lrange('a', 0, -1) == [b('1'), b('2'), b('3'), b('4')]
# SCAN COMMANDS
@skip_if_server_version_lt('2.8.0')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_scan(self, r):
await r.flushdb()
await r.set('a', 1)
await r.set('b', 2)
await r.set('c', 3)
cursor, keys = await r.scan()
assert cursor == 0
assert set(keys) == set([b('a'), b('b'), b('c')])
_, keys = await r.scan(match='a')
assert set(keys) == set([b('a')])
@skip_if_server_version_lt('2.8.0')
<|code_end|>
. Write the next line using the current file imports:
import binascii
import datetime
import pytest
import aredis
import time
from string import ascii_letters
from aredis.utils import (b, iteritems,
iterkeys, itervalues)
from aredis.commands.server import parse_info
from aredis.exceptions import (RedisError,
ResponseError,
DataError)
from .conftest import (skip_if_server_version_lt,
skip_python_vsersion_lt)
and context from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
#
# def skip_python_vsersion_lt(min_version):
# min_version = tuple(map(int, min_version.split('.')))
# check = sys.version_info[:2] < min_version
# return pytest.mark.skipif(check, reason="")
, which may include functions, classes, or code. Output only the next line. | @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
self.encoding = encoding
def _trans_type(self, content):
if isinstance(content, str):
content = content.encode(self.encoding)
elif isinstance(content, int):
<|code_end|>
. Write the next line using the current file imports:
import hashlib
import time
import zlib
import ujson as json
import json
from aredis.utils import b
from aredis.exceptions import (SerializeError,
CompressError)
and context from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# Path: aredis/exceptions.py
# class SerializeError(CacheError):
# pass
#
# class CompressError(CacheError):
# pass
, which may include functions, classes, or code. Output only the next line. | 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:
"""
Uses json to serialize and deserialize cache to str. You may implement
your own Serializer implemting `serialize` and `deserialize` methods.
"""
def __init__(self, encoding='utf-8'):
self.encoding = encoding
def _trans_type(self, content):
if isinstance(content, bytes):
content = content.decode(self.encoding)
if not isinstance(content, str):
raise TypeError('Wrong data type({}) to compress'.format(type(content)))
return content
def serialize(self, content):
try:
return json.dumps(content)
except Exception as exc:
<|code_end|>
, determine the next line of code. You have imports:
import hashlib
import time
import zlib
import ujson as json
import json
from aredis.utils import b
from aredis.exceptions import (SerializeError,
CompressError)
and context (class names, function names, or code) available:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# Path: aredis/exceptions.py
# class SerializeError(CacheError):
# pass
#
# class CompressError(CacheError):
# pass
. Output only the next line. | 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 = encoding
def _trans_type(self, content):
if isinstance(content, str):
content = content.encode(self.encoding)
elif isinstance(content, int):
content = b(str(content))
elif isinstance(content, float):
content = b(repr(content))
if not isinstance(content, bytes):
raise TypeError('Wrong data type({}) to compress'.format(type(content)))
return content
def compress(self, content):
content = self._trans_type(content)
if len(content) > self.min_length:
try:
return zlib.compress(content, self.preset)
except zlib.error as exc:
<|code_end|>
, generate the next line using the imports in this file:
import hashlib
import time
import zlib
import ujson as json
import json
from aredis.utils import b
from aredis.exceptions import (SerializeError,
CompressError)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# Path: aredis/exceptions.py
# class SerializeError(CacheError):
# pass
#
# class CompressError(CacheError):
# pass
. Output only the next line. | 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._stream = stream_reader
self.read_size = read_size
self._buffer = BytesIO()
# number of bytes written to the buffer from the socket
self.bytes_written = 0
# number of bytes read from the buffer
self.bytes_read = 0
@property
def length(self):
return self.bytes_written - self.bytes_read
async def _read_from_socket(self, length=None):
buf = self._buffer
buf.seek(self.bytes_written)
marker = 0
try:
while True:
data = await self._stream.read(self.read_size)
# an empty string indicates the server shutdown the socket
if isinstance(data, bytes) and len(data) == 0:
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context including class names, function names, and sometimes code from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | 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_DEPRECATED:
return await asyncio.wait_for(coroutine, timeout)
else:
return await asyncio.wait_for(coroutine, timeout, loop=loop)
<|code_end|>
. Use current file imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
. Output only the next line. | 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
response = await self._buffer.read(length)
# multi-bulk response
elif byte == '*':
length = int(response)
if length == -1:
return None
response = []
for i in range(length):
response.append(await self.read_response())
if isinstance(response, bytes) and self.encoding:
response = response.decode(self.encoding)
return response
class HiredisParser(BaseParser):
"""Parser class for connections using Hiredis"""
def __init__(self, read_size):
if not HIREDIS_AVAILABLE:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import inspect
import os
import socket
import ssl
import sys
import time
import warnings
import aredis.compat
import hiredis
from io import BytesIO
from aredis.exceptions import (ConnectionError, TimeoutError,
RedisError, ExecAbortError,
BusyLoadingError, NoScriptError,
ReadOnlyError, ResponseError,
InvalidResponse, AskError,
MovedError, TryAgainError,
ClusterDownError, ClusterCrossSlotError)
from aredis.utils import b, nativestr, LOOP_DEPRECATED
and context:
# Path: aredis/exceptions.py
# class ConnectionError(RedisError):
# pass
#
# class TimeoutError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class ExecAbortError(ResponseError):
# pass
#
# class BusyLoadingError(ConnectionError):
# pass
#
# class NoScriptError(ResponseError):
# pass
#
# class ReadOnlyError(ResponseError):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class InvalidResponse(RedisError):
# pass
#
# class AskError(ResponseError):
# """
# src node: MIGRATING to dst node
# get > ASK error
# ask dst node > ASKING command
# dst node: IMPORTING from src node
# asking command only affects next command
# any op will be allowed after asking command
# """
#
# def __init__(self, resp):
# """should only redirect to master node"""
# self.args = (resp,)
# self.message = resp
# slot_id, new_node = resp.split(' ')
# host, port = new_node.rsplit(':', 1)
# self.slot_id = int(slot_id)
# self.node_addr = self.host, self.port = host, int(port)
#
# class MovedError(AskError):
# pass
#
# class TryAgainError(ResponseError):
#
# def __init__(self, *args, **kwargs):
# pass
#
# class ClusterDownError(ClusterError, ResponseError):
#
# def __init__(self, resp):
# self.args = (resp,)
# self.message = resp
#
# class ClusterCrossSlotError(ResponseError):
# message = "Keys in request don't hash to the same slot"
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# LOOP_DEPRECATED = sys.version_info >= (3, 8)
which might include code, classes, or functions. Output only the next line. | raise RedisError("Hiredis is not installed") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.