_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q22800
|
StringCommandsMixin.mset
|
train
|
def mset(self, *args):
"""Set multiple keys to multiple values or unpack dict to keys & values.
:raises TypeError: if len of args is not event number
:raises TypeError: if len of args equals 1 and it is not a dict
"""
data = args
if len(args) == 1:
if not isinstance(args[0], dict):
raise TypeError("if one arg it should be a dict")
data = chain.from_iterable(args[0].items())
elif len(args) % 2 != 0:
raise TypeError("length of pairs must be even number")
fut = self.execute(b'MSET', *data)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22801
|
StringCommandsMixin.msetnx
|
train
|
def msetnx(self, key, value, *pairs):
"""Set multiple keys to multiple values,
only if none of the keys exist.
:raises TypeError: if len of pairs is not event number
"""
if len(pairs) % 2 != 0:
raise TypeError("length of pairs must be even number")
return self.execute(b'MSETNX', key, value, *pairs)
|
python
|
{
"resource": ""
}
|
q22802
|
StringCommandsMixin.psetex
|
train
|
def psetex(self, key, milliseconds, value):
"""Set the value and expiration in milliseconds of a key.
:raises TypeError: if milliseconds is not int
"""
if not isinstance(milliseconds, int):
raise TypeError("milliseconds argument must be int")
fut = self.execute(b'PSETEX', key, milliseconds, value)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22803
|
StringCommandsMixin.set
|
train
|
def set(self, key, value, *, expire=0, pexpire=0, exist=None):
"""Set the string value of a key.
:raises TypeError: if expire or pexpire is not int
"""
if expire and not isinstance(expire, int):
raise TypeError("expire argument must be int")
if pexpire and not isinstance(pexpire, int):
raise TypeError("pexpire argument must be int")
args = []
if expire:
args[:] = [b'EX', expire]
if pexpire:
args[:] = [b'PX', pexpire]
if exist is self.SET_IF_EXIST:
args.append(b'XX')
elif exist is self.SET_IF_NOT_EXIST:
args.append(b'NX')
fut = self.execute(b'SET', key, value, *args)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22804
|
StringCommandsMixin.setex
|
train
|
def setex(self, key, seconds, value):
"""Set the value and expiration of a key.
If seconds is float it will be multiplied by 1000
coerced to int and passed to `psetex` method.
:raises TypeError: if seconds is neither int nor float
"""
if isinstance(seconds, float):
return self.psetex(key, int(seconds * 1000), value)
if not isinstance(seconds, int):
raise TypeError("milliseconds argument must be int")
fut = self.execute(b'SETEX', key, seconds, value)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22805
|
StringCommandsMixin.setnx
|
train
|
def setnx(self, key, value):
"""Set the value of a key, only if the key does not exist."""
fut = self.execute(b'SETNX', key, value)
return wait_convert(fut, bool)
|
python
|
{
"resource": ""
}
|
q22806
|
StringCommandsMixin.setrange
|
train
|
def setrange(self, key, offset, value):
"""Overwrite part of a string at key starting at the specified offset.
:raises TypeError: if offset is not int
:raises ValueError: if offset less than 0
"""
if not isinstance(offset, int):
raise TypeError("offset argument must be int")
if offset < 0:
raise ValueError("offset must be greater equal 0")
return self.execute(b'SETRANGE', key, offset, value)
|
python
|
{
"resource": ""
}
|
q22807
|
GenericCommandsMixin.expire
|
train
|
def expire(self, key, timeout):
"""Set a timeout on key.
if timeout is float it will be multiplied by 1000
coerced to int and passed to `pexpire` method.
Otherwise raises TypeError if timeout argument is not int.
"""
if isinstance(timeout, float):
return self.pexpire(key, int(timeout * 1000))
if not isinstance(timeout, int):
raise TypeError(
"timeout argument must be int, not {!r}".format(timeout))
fut = self.execute(b'EXPIRE', key, timeout)
return wait_convert(fut, bool)
|
python
|
{
"resource": ""
}
|
q22808
|
GenericCommandsMixin.expireat
|
train
|
def expireat(self, key, timestamp):
"""Set expire timestamp on a key.
if timeout is float it will be multiplied by 1000
coerced to int and passed to `pexpireat` method.
Otherwise raises TypeError if timestamp argument is not int.
"""
if isinstance(timestamp, float):
return self.pexpireat(key, int(timestamp * 1000))
if not isinstance(timestamp, int):
raise TypeError("timestamp argument must be int, not {!r}"
.format(timestamp))
fut = self.execute(b'EXPIREAT', key, timestamp)
return wait_convert(fut, bool)
|
python
|
{
"resource": ""
}
|
q22809
|
GenericCommandsMixin.keys
|
train
|
def keys(self, pattern, *, encoding=_NOTSET):
"""Returns all keys matching pattern."""
return self.execute(b'KEYS', pattern, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22810
|
GenericCommandsMixin.migrate
|
train
|
def migrate(self, host, port, key, dest_db, timeout, *,
copy=False, replace=False):
"""Atomically transfer a key from a Redis instance to another one."""
if not isinstance(host, str):
raise TypeError("host argument must be str")
if not isinstance(timeout, int):
raise TypeError("timeout argument must be int")
if not isinstance(dest_db, int):
raise TypeError("dest_db argument must be int")
if not host:
raise ValueError("Got empty host")
if dest_db < 0:
raise ValueError("dest_db must be greater equal 0")
if timeout < 0:
raise ValueError("timeout must be greater equal 0")
flags = []
if copy:
flags.append(b'COPY')
if replace:
flags.append(b'REPLACE')
fut = self.execute(b'MIGRATE', host, port,
key, dest_db, timeout, *flags)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22811
|
GenericCommandsMixin.migrate_keys
|
train
|
def migrate_keys(self, host, port, keys, dest_db, timeout, *,
copy=False, replace=False):
"""Atomically transfer keys from one Redis instance to another one.
Keys argument must be list/tuple of keys to migrate.
"""
if not isinstance(host, str):
raise TypeError("host argument must be str")
if not isinstance(timeout, int):
raise TypeError("timeout argument must be int")
if not isinstance(dest_db, int):
raise TypeError("dest_db argument must be int")
if not isinstance(keys, (list, tuple)):
raise TypeError("keys argument must be list or tuple")
if not host:
raise ValueError("Got empty host")
if dest_db < 0:
raise ValueError("dest_db must be greater equal 0")
if timeout < 0:
raise ValueError("timeout must be greater equal 0")
if not keys:
raise ValueError("keys must not be empty")
flags = []
if copy:
flags.append(b'COPY')
if replace:
flags.append(b'REPLACE')
flags.append(b'KEYS')
flags.extend(keys)
fut = self.execute(b'MIGRATE', host, port,
"", dest_db, timeout, *flags)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22812
|
GenericCommandsMixin.move
|
train
|
def move(self, key, db):
"""Move key from currently selected database to specified destination.
:raises TypeError: if db is not int
:raises ValueError: if db is less than 0
"""
if not isinstance(db, int):
raise TypeError("db argument must be int, not {!r}".format(db))
if db < 0:
raise ValueError("db argument must be not less than 0, {!r}"
.format(db))
fut = self.execute(b'MOVE', key, db)
return wait_convert(fut, bool)
|
python
|
{
"resource": ""
}
|
q22813
|
GenericCommandsMixin.persist
|
train
|
def persist(self, key):
"""Remove the existing timeout on key."""
fut = self.execute(b'PERSIST', key)
return wait_convert(fut, bool)
|
python
|
{
"resource": ""
}
|
q22814
|
GenericCommandsMixin.pexpire
|
train
|
def pexpire(self, key, timeout):
"""Set a milliseconds timeout on key.
:raises TypeError: if timeout is not int
"""
if not isinstance(timeout, int):
raise TypeError("timeout argument must be int, not {!r}"
.format(timeout))
fut = self.execute(b'PEXPIRE', key, timeout)
return wait_convert(fut, bool)
|
python
|
{
"resource": ""
}
|
q22815
|
GenericCommandsMixin.pexpireat
|
train
|
def pexpireat(self, key, timestamp):
"""Set expire timestamp on key, timestamp in milliseconds.
:raises TypeError: if timeout is not int
"""
if not isinstance(timestamp, int):
raise TypeError("timestamp argument must be int, not {!r}"
.format(timestamp))
fut = self.execute(b'PEXPIREAT', key, timestamp)
return wait_convert(fut, bool)
|
python
|
{
"resource": ""
}
|
q22816
|
GenericCommandsMixin.rename
|
train
|
def rename(self, key, newkey):
"""Renames key to newkey.
:raises ValueError: if key == newkey
"""
if key == newkey:
raise ValueError("key and newkey are the same")
fut = self.execute(b'RENAME', key, newkey)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22817
|
GenericCommandsMixin.renamenx
|
train
|
def renamenx(self, key, newkey):
"""Renames key to newkey only if newkey does not exist.
:raises ValueError: if key == newkey
"""
if key == newkey:
raise ValueError("key and newkey are the same")
fut = self.execute(b'RENAMENX', key, newkey)
return wait_convert(fut, bool)
|
python
|
{
"resource": ""
}
|
q22818
|
GenericCommandsMixin.restore
|
train
|
def restore(self, key, ttl, value):
"""Creates a key associated with a value that is obtained via DUMP."""
return self.execute(b'RESTORE', key, ttl, value)
|
python
|
{
"resource": ""
}
|
q22819
|
GenericCommandsMixin.scan
|
train
|
def scan(self, cursor=0, match=None, count=None):
"""Incrementally iterate the keys space.
Usage example:
>>> match = 'something*'
>>> cur = b'0'
>>> while cur:
... cur, keys = await redis.scan(cur, match=match)
... for key in keys:
... print('Matched:', key)
"""
args = []
if match is not None:
args += [b'MATCH', match]
if count is not None:
args += [b'COUNT', count]
fut = self.execute(b'SCAN', cursor, *args)
return wait_convert(fut, lambda o: (int(o[0]), o[1]))
|
python
|
{
"resource": ""
}
|
q22820
|
GenericCommandsMixin.iscan
|
train
|
def iscan(self, *, match=None, count=None):
"""Incrementally iterate the keys space using async for.
Usage example:
>>> async for key in redis.iscan(match='something*'):
... print('Matched:', key)
"""
return _ScanIter(lambda cur: self.scan(cur,
match=match, count=count))
|
python
|
{
"resource": ""
}
|
q22821
|
GenericCommandsMixin.sort
|
train
|
def sort(self, key, *get_patterns,
by=None, offset=None, count=None,
asc=None, alpha=False, store=None):
"""Sort the elements in a list, set or sorted set."""
args = []
if by is not None:
args += [b'BY', by]
if offset is not None and count is not None:
args += [b'LIMIT', offset, count]
if get_patterns:
args += sum(([b'GET', pattern] for pattern in get_patterns), [])
if asc is not None:
args += [asc is True and b'ASC' or b'DESC']
if alpha:
args += [b'ALPHA']
if store is not None:
args += [b'STORE', store]
return self.execute(b'SORT', key, *args)
|
python
|
{
"resource": ""
}
|
q22822
|
GenericCommandsMixin.unlink
|
train
|
def unlink(self, key, *keys):
"""Delete a key asynchronously in another thread."""
return wait_convert(self.execute(b'UNLINK', key, *keys), int)
|
python
|
{
"resource": ""
}
|
q22823
|
HashCommandsMixin.hdel
|
train
|
def hdel(self, key, field, *fields):
"""Delete one or more hash fields."""
return self.execute(b'HDEL', key, field, *fields)
|
python
|
{
"resource": ""
}
|
q22824
|
HashCommandsMixin.hexists
|
train
|
def hexists(self, key, field):
"""Determine if hash field exists."""
fut = self.execute(b'HEXISTS', key, field)
return wait_convert(fut, bool)
|
python
|
{
"resource": ""
}
|
q22825
|
HashCommandsMixin.hget
|
train
|
def hget(self, key, field, *, encoding=_NOTSET):
"""Get the value of a hash field."""
return self.execute(b'HGET', key, field, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22826
|
HashCommandsMixin.hgetall
|
train
|
def hgetall(self, key, *, encoding=_NOTSET):
"""Get all the fields and values in a hash."""
fut = self.execute(b'HGETALL', key, encoding=encoding)
return wait_make_dict(fut)
|
python
|
{
"resource": ""
}
|
q22827
|
HashCommandsMixin.hincrbyfloat
|
train
|
def hincrbyfloat(self, key, field, increment=1.0):
"""Increment the float value of a hash field by the given number."""
fut = self.execute(b'HINCRBYFLOAT', key, field, increment)
return wait_convert(fut, float)
|
python
|
{
"resource": ""
}
|
q22828
|
HashCommandsMixin.hkeys
|
train
|
def hkeys(self, key, *, encoding=_NOTSET):
"""Get all the fields in a hash."""
return self.execute(b'HKEYS', key, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22829
|
HashCommandsMixin.hmget
|
train
|
def hmget(self, key, field, *fields, encoding=_NOTSET):
"""Get the values of all the given fields."""
return self.execute(b'HMGET', key, field, *fields, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22830
|
HashCommandsMixin.hset
|
train
|
def hset(self, key, field, value):
"""Set the string value of a hash field."""
return self.execute(b'HSET', key, field, value)
|
python
|
{
"resource": ""
}
|
q22831
|
HashCommandsMixin.hsetnx
|
train
|
def hsetnx(self, key, field, value):
"""Set the value of a hash field, only if the field does not exist."""
return self.execute(b'HSETNX', key, field, value)
|
python
|
{
"resource": ""
}
|
q22832
|
HashCommandsMixin.hvals
|
train
|
def hvals(self, key, *, encoding=_NOTSET):
"""Get all the values in a hash."""
return self.execute(b'HVALS', key, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22833
|
SortedSetCommandsMixin.zadd
|
train
|
def zadd(self, key, score, member, *pairs, exist=None):
"""Add one or more members to a sorted set or update its score.
:raises TypeError: score not int or float
:raises TypeError: length of pairs is not even number
"""
if not isinstance(score, (int, float)):
raise TypeError("score argument must be int or float")
if len(pairs) % 2 != 0:
raise TypeError("length of pairs must be even number")
scores = (item for i, item in enumerate(pairs) if i % 2 == 0)
if any(not isinstance(s, (int, float)) for s in scores):
raise TypeError("all scores must be int or float")
args = []
if exist is self.ZSET_IF_EXIST:
args.append(b'XX')
elif exist is self.ZSET_IF_NOT_EXIST:
args.append(b'NX')
args.extend([score, member])
if pairs:
args.extend(pairs)
return self.execute(b'ZADD', key, *args)
|
python
|
{
"resource": ""
}
|
q22834
|
SortedSetCommandsMixin.zcount
|
train
|
def zcount(self, key, min=float('-inf'), max=float('inf'),
*, exclude=None):
"""Count the members in a sorted set with scores
within the given values.
:raises TypeError: min or max is not float or int
:raises ValueError: if min greater than max
"""
if not isinstance(min, (int, float)):
raise TypeError("min argument must be int or float")
if not isinstance(max, (int, float)):
raise TypeError("max argument must be int or float")
if min > max:
raise ValueError("min could not be greater than max")
return self.execute(b'ZCOUNT', key,
*_encode_min_max(exclude, min, max))
|
python
|
{
"resource": ""
}
|
q22835
|
SortedSetCommandsMixin.zincrby
|
train
|
def zincrby(self, key, increment, member):
"""Increment the score of a member in a sorted set.
:raises TypeError: increment is not float or int
"""
if not isinstance(increment, (int, float)):
raise TypeError("increment argument must be int or float")
fut = self.execute(b'ZINCRBY', key, increment, member)
return wait_convert(fut, int_or_float)
|
python
|
{
"resource": ""
}
|
q22836
|
SortedSetCommandsMixin.zrem
|
train
|
def zrem(self, key, member, *members):
"""Remove one or more members from a sorted set."""
return self.execute(b'ZREM', key, member, *members)
|
python
|
{
"resource": ""
}
|
q22837
|
SortedSetCommandsMixin.zremrangebylex
|
train
|
def zremrangebylex(self, key, min=b'-', max=b'+',
include_min=True, include_max=True):
"""Remove all members in a sorted set between the given
lexicographical range.
:raises TypeError: if min is not bytes
:raises TypeError: if max is not bytes
"""
if not isinstance(min, bytes): # FIXME
raise TypeError("min argument must be bytes")
if not isinstance(max, bytes): # FIXME
raise TypeError("max argument must be bytes")
if not min == b'-':
min = (b'[' if include_min else b'(') + min
if not max == b'+':
max = (b'[' if include_max else b'(') + max
return self.execute(b'ZREMRANGEBYLEX', key, min, max)
|
python
|
{
"resource": ""
}
|
q22838
|
SortedSetCommandsMixin.zremrangebyrank
|
train
|
def zremrangebyrank(self, key, start, stop):
"""Remove all members in a sorted set within the given indexes.
:raises TypeError: if start is not int
:raises TypeError: if stop is not int
"""
if not isinstance(start, int):
raise TypeError("start argument must be int")
if not isinstance(stop, int):
raise TypeError("stop argument must be int")
return self.execute(b'ZREMRANGEBYRANK', key, start, stop)
|
python
|
{
"resource": ""
}
|
q22839
|
SortedSetCommandsMixin.zremrangebyscore
|
train
|
def zremrangebyscore(self, key, min=float('-inf'), max=float('inf'),
*, exclude=None):
"""Remove all members in a sorted set within the given scores.
:raises TypeError: if min or max is not int or float
"""
if not isinstance(min, (int, float)):
raise TypeError("min argument must be int or float")
if not isinstance(max, (int, float)):
raise TypeError("max argument must be int or float")
min, max = _encode_min_max(exclude, min, max)
return self.execute(b'ZREMRANGEBYSCORE', key, min, max)
|
python
|
{
"resource": ""
}
|
q22840
|
SortedSetCommandsMixin.zrevrange
|
train
|
def zrevrange(self, key, start, stop, withscores=False, encoding=_NOTSET):
"""Return a range of members in a sorted set, by index,
with scores ordered from high to low.
:raises TypeError: if start or stop is not int
"""
if not isinstance(start, int):
raise TypeError("start argument must be int")
if not isinstance(stop, int):
raise TypeError("stop argument must be int")
if withscores:
args = [b'WITHSCORES']
else:
args = []
fut = self.execute(b'ZREVRANGE', key, start, stop, *args,
encoding=encoding)
if withscores:
return wait_convert(fut, pairs_int_or_float)
return fut
|
python
|
{
"resource": ""
}
|
q22841
|
SortedSetCommandsMixin.zrevrangebyscore
|
train
|
def zrevrangebyscore(self, key, max=float('inf'), min=float('-inf'),
*, exclude=None, withscores=False,
offset=None, count=None, encoding=_NOTSET):
"""Return a range of members in a sorted set, by score,
with scores ordered from high to low.
:raises TypeError: if min or max is not float or int
:raises TypeError: if both offset and count are not specified
:raises TypeError: if offset is not int
:raises TypeError: if count is not int
"""
if not isinstance(min, (int, float)):
raise TypeError("min argument must be int or float")
if not isinstance(max, (int, float)):
raise TypeError("max argument must be int or float")
if (offset is not None and count is None) or \
(count is not None and offset is None):
raise TypeError("offset and count must both be specified")
if offset is not None and not isinstance(offset, int):
raise TypeError("offset argument must be int")
if count is not None and not isinstance(count, int):
raise TypeError("count argument must be int")
min, max = _encode_min_max(exclude, min, max)
args = []
if withscores:
args = [b'WITHSCORES']
if offset is not None and count is not None:
args.extend([b'LIMIT', offset, count])
fut = self.execute(b'ZREVRANGEBYSCORE', key, max, min, *args,
encoding=encoding)
if withscores:
return wait_convert(fut, pairs_int_or_float)
return fut
|
python
|
{
"resource": ""
}
|
q22842
|
SortedSetCommandsMixin.zscore
|
train
|
def zscore(self, key, member):
"""Get the score associated with the given member in a sorted set."""
fut = self.execute(b'ZSCORE', key, member)
return wait_convert(fut, optional_int_or_float)
|
python
|
{
"resource": ""
}
|
q22843
|
SortedSetCommandsMixin.zunionstore
|
train
|
def zunionstore(self, destkey, key, *keys,
with_weights=False, aggregate=None):
"""Add multiple sorted sets and store result in a new key."""
keys = (key,) + keys
numkeys = len(keys)
args = []
if with_weights:
assert all(isinstance(val, (list, tuple)) for val in keys), (
"All key arguments must be (key, weight) tuples")
weights = ['WEIGHTS']
for key, weight in keys:
args.append(key)
weights.append(weight)
args.extend(weights)
else:
args.extend(keys)
if aggregate is self.ZSET_AGGREGATE_SUM:
args.extend(('AGGREGATE', 'SUM'))
elif aggregate is self.ZSET_AGGREGATE_MAX:
args.extend(('AGGREGATE', 'MAX'))
elif aggregate is self.ZSET_AGGREGATE_MIN:
args.extend(('AGGREGATE', 'MIN'))
fut = self.execute(b'ZUNIONSTORE', destkey, numkeys, *args)
return fut
|
python
|
{
"resource": ""
}
|
q22844
|
SortedSetCommandsMixin.zscan
|
train
|
def zscan(self, key, cursor=0, match=None, count=None):
"""Incrementally iterate sorted sets elements and associated scores."""
args = []
if match is not None:
args += [b'MATCH', match]
if count is not None:
args += [b'COUNT', count]
fut = self.execute(b'ZSCAN', key, cursor, *args)
def _converter(obj):
return (int(obj[0]), pairs_int_or_float(obj[1]))
return wait_convert(fut, _converter)
|
python
|
{
"resource": ""
}
|
q22845
|
SortedSetCommandsMixin.zpopmin
|
train
|
def zpopmin(self, key, count=None, *, encoding=_NOTSET):
"""Removes and returns up to count members with the lowest scores
in the sorted set stored at key.
:raises TypeError: if count is not int
"""
if count is not None and not isinstance(count, int):
raise TypeError("count argument must be int")
args = []
if count is not None:
args.extend([count])
fut = self.execute(b'ZPOPMIN', key, *args, encoding=encoding)
return fut
|
python
|
{
"resource": ""
}
|
q22846
|
SortedSetCommandsMixin.zpopmax
|
train
|
def zpopmax(self, key, count=None, *, encoding=_NOTSET):
"""Removes and returns up to count members with the highest scores
in the sorted set stored at key.
:raises TypeError: if count is not int
"""
if count is not None and not isinstance(count, int):
raise TypeError("count argument must be int")
args = []
if count is not None:
args.extend([count])
fut = self.execute(b'ZPOPMAX', key, *args, encoding=encoding)
return fut
|
python
|
{
"resource": ""
}
|
q22847
|
parse_messages_by_stream
|
train
|
def parse_messages_by_stream(messages_by_stream):
""" Parse messages returned by stream
Messages returned by XREAD arrive in the form:
[stream_name,
[
[message_id, [key1, value1, key2, value2, ...]],
...
],
...
]
Here we parse this into (with the help of the above parse_messages()
function):
[
[stream_name, message_id, OrderedDict(
(key1, value1),
(key2, value2),.
...
)],
...
]
"""
if messages_by_stream is None:
return []
parsed = []
for stream, messages in messages_by_stream:
for message_id, fields in parse_messages(messages):
parsed.append((stream, message_id, fields))
return parsed
|
python
|
{
"resource": ""
}
|
q22848
|
StreamCommandsMixin.xadd
|
train
|
def xadd(self, stream, fields, message_id=b'*', max_len=None,
exact_len=False):
"""Add a message to a stream."""
args = []
if max_len is not None:
if exact_len:
args.extend((b'MAXLEN', max_len))
else:
args.extend((b'MAXLEN', b'~', max_len))
args.append(message_id)
for k, v in fields.items():
args.extend([k, v])
return self.execute(b'XADD', stream, *args)
|
python
|
{
"resource": ""
}
|
q22849
|
StreamCommandsMixin.xrange
|
train
|
def xrange(self, stream, start='-', stop='+', count=None):
"""Retrieve messages from a stream."""
if count is not None:
extra = ['COUNT', count]
else:
extra = []
fut = self.execute(b'XRANGE', stream, start, stop, *extra)
return wait_convert(fut, parse_messages)
|
python
|
{
"resource": ""
}
|
q22850
|
StreamCommandsMixin.xrevrange
|
train
|
def xrevrange(self, stream, start='+', stop='-', count=None):
"""Retrieve messages from a stream in reverse order."""
if count is not None:
extra = ['COUNT', count]
else:
extra = []
fut = self.execute(b'XREVRANGE', stream, start, stop, *extra)
return wait_convert(fut, parse_messages)
|
python
|
{
"resource": ""
}
|
q22851
|
StreamCommandsMixin.xread
|
train
|
def xread(self, streams, timeout=0, count=None, latest_ids=None):
"""Perform a blocking read on the given stream
:raises ValueError: if the length of streams and latest_ids do
not match
"""
args = self._xread(streams, timeout, count, latest_ids)
fut = self.execute(b'XREAD', *args)
return wait_convert(fut, parse_messages_by_stream)
|
python
|
{
"resource": ""
}
|
q22852
|
StreamCommandsMixin.xread_group
|
train
|
def xread_group(self, group_name, consumer_name, streams, timeout=0,
count=None, latest_ids=None):
"""Perform a blocking read on the given stream as part of a consumer group
:raises ValueError: if the length of streams and latest_ids do
not match
"""
args = self._xread(streams, timeout, count, latest_ids)
fut = self.execute(
b'XREADGROUP', b'GROUP', group_name, consumer_name, *args
)
return wait_convert(fut, parse_messages_by_stream)
|
python
|
{
"resource": ""
}
|
q22853
|
StreamCommandsMixin.xgroup_create
|
train
|
def xgroup_create(self, stream, group_name, latest_id='$', mkstream=False):
"""Create a consumer group"""
args = [b'CREATE', stream, group_name, latest_id]
if mkstream:
args.append(b'MKSTREAM')
fut = self.execute(b'XGROUP', *args)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22854
|
StreamCommandsMixin.xgroup_setid
|
train
|
def xgroup_setid(self, stream, group_name, latest_id='$'):
"""Set the latest ID for a consumer group"""
fut = self.execute(b'XGROUP', b'SETID', stream, group_name, latest_id)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22855
|
StreamCommandsMixin.xgroup_destroy
|
train
|
def xgroup_destroy(self, stream, group_name):
"""Delete a consumer group"""
fut = self.execute(b'XGROUP', b'DESTROY', stream, group_name)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22856
|
StreamCommandsMixin.xgroup_delconsumer
|
train
|
def xgroup_delconsumer(self, stream, group_name, consumer_name):
"""Delete a specific consumer from a group"""
fut = self.execute(
b'XGROUP', b'DELCONSUMER', stream, group_name, consumer_name
)
return wait_convert(fut, int)
|
python
|
{
"resource": ""
}
|
q22857
|
StreamCommandsMixin.xpending
|
train
|
def xpending(self, stream, group_name, start=None, stop=None, count=None,
consumer=None):
"""Get information on pending messages for a stream
Returned data will vary depending on the presence (or not)
of the start/stop/count parameters. For more details see:
https://redis.io/commands/xpending
:raises ValueError: if the start/stop/count parameters are only
partially specified
"""
# Returns: total pel messages, min id, max id, count
ssc = [start, stop, count]
ssc_count = len([v for v in ssc if v is not None])
if ssc_count != 3 and ssc_count != 0:
raise ValueError(
'Either specify non or all of the start/stop/count arguments'
)
if not any(ssc):
ssc = []
args = [stream, group_name] + ssc
if consumer:
args.append(consumer)
return self.execute(b'XPENDING', *args)
|
python
|
{
"resource": ""
}
|
q22858
|
StreamCommandsMixin.xclaim
|
train
|
def xclaim(self, stream, group_name, consumer_name, min_idle_time,
id, *ids):
"""Claim a message for a given consumer"""
fut = self.execute(
b'XCLAIM', stream, group_name, consumer_name, min_idle_time,
id, *ids
)
return wait_convert(fut, parse_messages)
|
python
|
{
"resource": ""
}
|
q22859
|
StreamCommandsMixin.xack
|
train
|
def xack(self, stream, group_name, id, *ids):
"""Acknowledge a message for a given consumer group"""
return self.execute(b'XACK', stream, group_name, id, *ids)
|
python
|
{
"resource": ""
}
|
q22860
|
StreamCommandsMixin.xinfo_consumers
|
train
|
def xinfo_consumers(self, stream, group_name):
"""Retrieve consumers of a consumer group"""
fut = self.execute(b'XINFO', b'CONSUMERS', stream, group_name)
return wait_convert(fut, parse_lists_to_dicts)
|
python
|
{
"resource": ""
}
|
q22861
|
StreamCommandsMixin.xinfo_groups
|
train
|
def xinfo_groups(self, stream):
"""Retrieve the consumer groups for a stream"""
fut = self.execute(b'XINFO', b'GROUPS', stream)
return wait_convert(fut, parse_lists_to_dicts)
|
python
|
{
"resource": ""
}
|
q22862
|
StreamCommandsMixin.xinfo_stream
|
train
|
def xinfo_stream(self, stream):
"""Retrieve information about the given stream."""
fut = self.execute(b'XINFO', b'STREAM', stream)
return wait_make_dict(fut)
|
python
|
{
"resource": ""
}
|
q22863
|
StreamCommandsMixin.xinfo_help
|
train
|
def xinfo_help(self):
"""Retrieve help regarding the ``XINFO`` sub-commands"""
fut = self.execute(b'XINFO', b'HELP')
return wait_convert(fut, lambda l: b'\n'.join(l))
|
python
|
{
"resource": ""
}
|
q22864
|
Lock.acquire
|
train
|
def acquire(self):
"""Acquire a lock.
This method blocks until the lock is unlocked, then sets it to
locked and returns True.
"""
if not self._locked and all(w.cancelled() for w in self._waiters):
self._locked = True
return True
fut = self._loop.create_future()
self._waiters.append(fut)
try:
yield from fut
self._locked = True
return True
except asyncio.CancelledError:
if not self._locked: # pragma: no cover
self._wake_up_first()
raise
finally:
self._waiters.remove(fut)
|
python
|
{
"resource": ""
}
|
q22865
|
Lock._wake_up_first
|
train
|
def _wake_up_first(self):
"""Wake up the first waiter who isn't cancelled."""
for fut in self._waiters:
if not fut.done():
fut.set_result(True)
break
|
python
|
{
"resource": ""
}
|
q22866
|
ClusterCommandsMixin.cluster_add_slots
|
train
|
def cluster_add_slots(self, slot, *slots):
"""Assign new hash slots to receiving node."""
slots = (slot,) + slots
if not all(isinstance(s, int) for s in slots):
raise TypeError("All parameters must be of type int")
fut = self.execute(b'CLUSTER', b'ADDSLOTS', *slots)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22867
|
ClusterCommandsMixin.cluster_count_key_in_slots
|
train
|
def cluster_count_key_in_slots(self, slot):
"""Return the number of local keys in the specified hash slot."""
if not isinstance(slot, int):
raise TypeError("Expected slot to be of type int, got {}"
.format(type(slot)))
return self.execute(b'CLUSTER', b'COUNTKEYSINSLOT', slot)
|
python
|
{
"resource": ""
}
|
q22868
|
ClusterCommandsMixin.cluster_del_slots
|
train
|
def cluster_del_slots(self, slot, *slots):
"""Set hash slots as unbound in receiving node."""
slots = (slot,) + slots
if not all(isinstance(s, int) for s in slots):
raise TypeError("All parameters must be of type int")
fut = self.execute(b'CLUSTER', b'DELSLOTS', *slots)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22869
|
ClusterCommandsMixin.cluster_forget
|
train
|
def cluster_forget(self, node_id):
"""Remove a node from the nodes table."""
fut = self.execute(b'CLUSTER', b'FORGET', node_id)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22870
|
ClusterCommandsMixin.cluster_get_keys_in_slots
|
train
|
def cluster_get_keys_in_slots(self, slot, count, *, encoding):
"""Return local key names in the specified hash slot."""
return self.execute(b'CLUSTER', b'GETKEYSINSLOT', slot, count,
encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22871
|
ClusterCommandsMixin.cluster_replicate
|
train
|
def cluster_replicate(self, node_id):
"""Reconfigure a node as a slave of the specified master node."""
fut = self.execute(b'CLUSTER', b'REPLICATE', node_id)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22872
|
ClusterCommandsMixin.cluster_reset
|
train
|
def cluster_reset(self, *, hard=False):
"""Reset a Redis Cluster node."""
reset = hard and b'HARD' or b'SOFT'
fut = self.execute(b'CLUSTER', b'RESET', reset)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22873
|
ClusterCommandsMixin.cluster_set_config_epoch
|
train
|
def cluster_set_config_epoch(self, config_epoch):
"""Set the configuration epoch in a new node."""
fut = self.execute(b'CLUSTER', b'SET-CONFIG-EPOCH', config_epoch)
return wait_ok(fut)
|
python
|
{
"resource": ""
}
|
q22874
|
create_sentinel_pool
|
train
|
async def create_sentinel_pool(sentinels, *, db=None, password=None,
encoding=None, minsize=1, maxsize=10,
ssl=None, parser=None, timeout=0.2, loop=None):
"""Create SentinelPool."""
# FIXME: revise default timeout value
assert isinstance(sentinels, (list, tuple)), sentinels
if loop is None:
loop = asyncio.get_event_loop()
pool = SentinelPool(sentinels, db=db,
password=password,
ssl=ssl,
encoding=encoding,
parser=parser,
minsize=minsize,
maxsize=maxsize,
timeout=timeout,
loop=loop)
await pool.discover()
return pool
|
python
|
{
"resource": ""
}
|
q22875
|
SentinelPool.master_for
|
train
|
def master_for(self, service):
"""Returns wrapper to master's pool for requested service."""
# TODO: make it coroutine and connect minsize connections
if service not in self._masters:
self._masters[service] = ManagedPool(
self, service, is_master=True,
db=self._redis_db,
password=self._redis_password,
encoding=self._redis_encoding,
minsize=self._redis_minsize,
maxsize=self._redis_maxsize,
ssl=self._redis_ssl,
parser=self._parser_class,
loop=self._loop)
return self._masters[service]
|
python
|
{
"resource": ""
}
|
q22876
|
SentinelPool.slave_for
|
train
|
def slave_for(self, service):
"""Returns wrapper to slave's pool for requested service."""
# TODO: make it coroutine and connect minsize connections
if service not in self._slaves:
self._slaves[service] = ManagedPool(
self, service, is_master=False,
db=self._redis_db,
password=self._redis_password,
encoding=self._redis_encoding,
minsize=self._redis_minsize,
maxsize=self._redis_maxsize,
ssl=self._redis_ssl,
parser=self._parser_class,
loop=self._loop)
return self._slaves[service]
|
python
|
{
"resource": ""
}
|
q22877
|
SentinelPool.execute
|
train
|
def execute(self, command, *args, **kwargs):
"""Execute sentinel command."""
# TODO: choose pool
# kwargs can be used to control which sentinel to use
if self.closed:
raise PoolClosedError("Sentinel pool is closed")
for pool in self._pools:
return pool.execute(command, *args, **kwargs)
|
python
|
{
"resource": ""
}
|
q22878
|
SentinelPool.discover
|
train
|
async def discover(self, timeout=None): # TODO: better name?
"""Discover sentinels and all monitored services within given timeout.
If no sentinels discovered within timeout: TimeoutError is raised.
If some sentinels were discovered but not all — it is ok.
If not all monitored services (masters/slaves) discovered
(or connections established) — it is ok.
TBD: what if some sentinels/services unreachable;
"""
# TODO: check not closed
# TODO: discovery must be done with some customizable timeout.
if timeout is None:
timeout = self.discover_timeout
tasks = []
pools = []
for addr in self._sentinels: # iterate over unordered set
tasks.append(self._connect_sentinel(addr, timeout, pools))
done, pending = await asyncio.wait(tasks, loop=self._loop,
return_when=ALL_COMPLETED)
assert not pending, ("Expected all tasks to complete", done, pending)
for task in done:
result = task.result()
if isinstance(result, Exception):
continue # FIXME
if not pools:
raise Exception("Could not connect to any sentinel")
pools, self._pools[:] = self._pools[:], pools
# TODO: close current connections
for pool in pools:
pool.close()
await pool.wait_closed()
# TODO: discover peer sentinels
for pool in self._pools:
await pool.execute_pubsub(
b'psubscribe', self._monitor.pattern('*'))
|
python
|
{
"resource": ""
}
|
q22879
|
SentinelPool._connect_sentinel
|
train
|
async def _connect_sentinel(self, address, timeout, pools):
"""Try to connect to specified Sentinel returning either
connections pool or exception.
"""
try:
with async_timeout(timeout, loop=self._loop):
pool = await create_pool(
address, minsize=1, maxsize=2,
parser=self._parser_class,
loop=self._loop)
pools.append(pool)
return pool
except asyncio.TimeoutError as err:
sentinel_logger.debug(
"Failed to connect to Sentinel(%r) within %ss timeout",
address, timeout)
return err
except Exception as err:
sentinel_logger.debug(
"Error connecting to Sentinel(%r): %r", address, err)
return err
|
python
|
{
"resource": ""
}
|
q22880
|
SentinelPool.discover_master
|
train
|
async def discover_master(self, service, timeout):
"""Perform Master discovery for specified service."""
# TODO: get lock
idle_timeout = timeout
# FIXME: single timeout used 4 times;
# meaning discovery can take up to:
# 3 * timeout * (sentinels count)
#
# having one global timeout also can leed to
# a problem when not all sentinels are checked.
# use a copy, cause pools can change
pools = self._pools[:]
for sentinel in pools:
try:
with async_timeout(timeout, loop=self._loop):
address = await self._get_masters_address(
sentinel, service)
pool = self._masters[service]
with async_timeout(timeout, loop=self._loop), \
contextlib.ExitStack() as stack:
conn = await pool._create_new_connection(address)
stack.callback(conn.close)
await self._verify_service_role(conn, 'master')
stack.pop_all()
return conn
except asyncio.CancelledError:
# we must correctly handle CancelledError(s):
# application may be stopped or function can be cancelled
# by outer timeout, so we must stop the look up.
raise
except asyncio.TimeoutError:
continue
except DiscoverError as err:
sentinel_logger.debug("DiscoverError(%r, %s): %r",
sentinel, service, err)
await asyncio.sleep(idle_timeout, loop=self._loop)
continue
except RedisError as err:
raise MasterReplyError("Service {} error".format(service), err)
except Exception:
# TODO: clear (drop) connections to schedule reconnect
await asyncio.sleep(idle_timeout, loop=self._loop)
continue
else:
raise MasterNotFoundError("No master found for {}".format(service))
|
python
|
{
"resource": ""
}
|
q22881
|
SentinelPool.discover_slave
|
train
|
async def discover_slave(self, service, timeout, **kwargs):
"""Perform Slave discovery for specified service."""
# TODO: use kwargs to change how slaves are picked up
# (eg: round-robin, priority, random, etc)
idle_timeout = timeout
pools = self._pools[:]
for sentinel in pools:
try:
with async_timeout(timeout, loop=self._loop):
address = await self._get_slave_address(
sentinel, service) # add **kwargs
pool = self._slaves[service]
with async_timeout(timeout, loop=self._loop), \
contextlib.ExitStack() as stack:
conn = await pool._create_new_connection(address)
stack.callback(conn.close)
await self._verify_service_role(conn, 'slave')
stack.pop_all()
return conn
except asyncio.CancelledError:
raise
except asyncio.TimeoutError:
continue
except DiscoverError:
await asyncio.sleep(idle_timeout, loop=self._loop)
continue
except RedisError as err:
raise SlaveReplyError("Service {} error".format(service), err)
except Exception:
await asyncio.sleep(idle_timeout, loop=self._loop)
continue
raise SlaveNotFoundError("No slave found for {}".format(service))
|
python
|
{
"resource": ""
}
|
q22882
|
Redis.echo
|
train
|
def echo(self, message, *, encoding=_NOTSET):
"""Echo the given string."""
return self.execute('ECHO', message, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22883
|
Redis.ping
|
train
|
def ping(self, message=_NOTSET, *, encoding=_NOTSET):
"""Ping the server.
Accept optional echo message.
"""
if message is not _NOTSET:
args = (message,)
else:
args = ()
return self.execute('PING', *args, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22884
|
SetCommandsMixin.sadd
|
train
|
def sadd(self, key, member, *members):
"""Add one or more members to a set."""
return self.execute(b'SADD', key, member, *members)
|
python
|
{
"resource": ""
}
|
q22885
|
SetCommandsMixin.sdiffstore
|
train
|
def sdiffstore(self, destkey, key, *keys):
"""Subtract multiple sets and store the resulting set in a key."""
return self.execute(b'SDIFFSTORE', destkey, key, *keys)
|
python
|
{
"resource": ""
}
|
q22886
|
SetCommandsMixin.sinterstore
|
train
|
def sinterstore(self, destkey, key, *keys):
"""Intersect multiple sets and store the resulting set in a key."""
return self.execute(b'SINTERSTORE', destkey, key, *keys)
|
python
|
{
"resource": ""
}
|
q22887
|
SetCommandsMixin.smembers
|
train
|
def smembers(self, key, *, encoding=_NOTSET):
"""Get all the members in a set."""
return self.execute(b'SMEMBERS', key, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22888
|
SetCommandsMixin.smove
|
train
|
def smove(self, sourcekey, destkey, member):
"""Move a member from one set to another."""
return self.execute(b'SMOVE', sourcekey, destkey, member)
|
python
|
{
"resource": ""
}
|
q22889
|
SetCommandsMixin.spop
|
train
|
def spop(self, key, count=None, *, encoding=_NOTSET):
"""Remove and return one or multiple random members from a set."""
args = [key]
if count is not None:
args.append(count)
return self.execute(b'SPOP', *args, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22890
|
SetCommandsMixin.srandmember
|
train
|
def srandmember(self, key, count=None, *, encoding=_NOTSET):
"""Get one or multiple random members from a set."""
args = [key]
count is not None and args.append(count)
return self.execute(b'SRANDMEMBER', *args, encoding=encoding)
|
python
|
{
"resource": ""
}
|
q22891
|
SetCommandsMixin.srem
|
train
|
def srem(self, key, member, *members):
"""Remove one or more members from a set."""
return self.execute(b'SREM', key, member, *members)
|
python
|
{
"resource": ""
}
|
q22892
|
SetCommandsMixin.sunionstore
|
train
|
def sunionstore(self, destkey, key, *keys):
"""Add multiple sets and store the resulting set in a key."""
return self.execute(b'SUNIONSTORE', destkey, key, *keys)
|
python
|
{
"resource": ""
}
|
q22893
|
SetCommandsMixin.sscan
|
train
|
def sscan(self, key, cursor=0, match=None, count=None):
"""Incrementally iterate Set elements."""
tokens = [key, cursor]
match is not None and tokens.extend([b'MATCH', match])
count is not None and tokens.extend([b'COUNT', count])
fut = self.execute(b'SSCAN', *tokens)
return wait_convert(fut, lambda obj: (int(obj[0]), obj[1]))
|
python
|
{
"resource": ""
}
|
q22894
|
SetCommandsMixin.isscan
|
train
|
def isscan(self, key, *, match=None, count=None):
"""Incrementally iterate set elements using async for.
Usage example:
>>> async for val in redis.isscan(key, match='something*'):
... print('Matched:', val)
"""
return _ScanIter(lambda cur: self.sscan(key, cur,
match=match,
count=count))
|
python
|
{
"resource": ""
}
|
q22895
|
HyperLogLogCommandsMixin.pfadd
|
train
|
def pfadd(self, key, value, *values):
"""Adds the specified elements to the specified HyperLogLog."""
return self.execute(b'PFADD', key, value, *values)
|
python
|
{
"resource": ""
}
|
q22896
|
main
|
train
|
async def main():
"""Scan command example."""
redis = await aioredis.create_redis(
'redis://localhost')
await redis.mset('key:1', 'value1', 'key:2', 'value2')
cur = b'0' # set initial cursor to 0
while cur:
cur, keys = await redis.scan(cur, match='key:*')
print("Iteration results:", keys)
redis.close()
await redis.wait_closed()
|
python
|
{
"resource": ""
}
|
q22897
|
find_additional_properties
|
train
|
def find_additional_properties(instance, schema):
"""
Return the set of additional properties for the given ``instance``.
Weeds out properties that should have been validated by ``properties`` and
/ or ``patternProperties``.
Assumes ``instance`` is dict-like already.
"""
properties = schema.get("properties", {})
patterns = "|".join(schema.get("patternProperties", {}))
for property in instance:
if property not in properties:
if patterns and re.search(patterns, property):
continue
yield property
|
python
|
{
"resource": ""
}
|
q22898
|
extras_msg
|
train
|
def extras_msg(extras):
"""
Create an error message for extra items or properties.
"""
if len(extras) == 1:
verb = "was"
else:
verb = "were"
return ", ".join(repr(extra) for extra in extras), verb
|
python
|
{
"resource": ""
}
|
q22899
|
types_msg
|
train
|
def types_msg(instance, types):
"""
Create an error message for a failure to match the given types.
If the ``instance`` is an object and contains a ``name`` property, it will
be considered to be a description of that object and used as its type.
Otherwise the message is simply the reprs of the given ``types``.
"""
reprs = []
for type in types:
try:
reprs.append(repr(type["name"]))
except Exception:
reprs.append(repr(type))
return "%r is not of type %s" % (instance, ", ".join(reprs))
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.