INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Suspend all the Redis clients for the specified amount of time: param timeout: milliseconds to pause clients | def client_pause(self, timeout):
"""
Suspend all the Redis clients for the specified amount of time
:param timeout: milliseconds to pause clients
"""
if not isinstance(timeout, (int, long)):
raise DataError("CLIENT PAUSE timeout must be an integer")
return sel... |
Delete all keys in all databases on the current host. | def flushall(self, asynchronous=False):
"""
Delete all keys in all databases on the current host.
``asynchronous`` indicates whether the operation is
executed asynchronously by the server.
"""
args = []
if asynchronous:
args.append(Token.get_token('AS... |
Migrate 1 or more keys from the current Redis server to a different server specified by the host port and destination_db. | def migrate(self, host, port, keys, destination_db, timeout,
copy=False, replace=False, auth=None):
"""
Migrate 1 or more keys from the current Redis server to a different
server specified by the ``host``, ``port`` and ``destination_db``.
The ``timeout``, specified in mi... |
Return the encoding idletime or refcount about the key | def object(self, infotype, key):
"Return the encoding, idletime, or refcount about the key"
return self.execute_command('OBJECT', infotype, key, infotype=infotype) |
Return the total memory usage for key its value and associated administrative overheads. | def memory_usage(self, key, samples=None):
"""
Return the total memory usage for key, its value and associated
administrative overheads.
For nested data structures, ``samples`` is the number of elements to
sample. If left unspecified, the server's default is 5. Use 0 to sample
... |
Shutdown the Redis server. If Redis has persistence configured data will be flushed before shutdown. If the save option is set a data flush will be attempted even if there is no persistence configured. If the nosave option is set no data flush will be attempted. The save and nosave options cannot both be set. | def shutdown(self, save=False, nosave=False):
"""Shutdown the Redis server. If Redis has persistence configured,
data will be flushed before shutdown. If the "save" option is set,
a data flush will be attempted even if there is no persistence
configured. If the "nosave" option is set,... |
Set the server to be a replicated slave of the instance identified by the host and port. If called without arguments the instance is promoted to a master instead. | def slaveof(self, host=None, port=None):
"""
Set the server to be a replicated slave of the instance identified
by the ``host`` and ``port``. If called without arguments, the
instance is promoted to a master instead.
"""
if host is None and port is None:
retur... |
Perform a bitwise operation using operation between keys and store the result in dest. | def bitop(self, operation, dest, *keys):
"""
Perform a bitwise operation using ``operation`` between ``keys`` and
store the result in ``dest``.
"""
return self.execute_command('BITOP', operation, dest, *keys) |
Return the position of the first bit set to 1 or 0 in a string. start and end difines search range. The range is interpreted as a range of bytes and not a range of bits so start = 0 and end = 2 means to look at the first three bytes. | def bitpos(self, key, bit, start=None, end=None):
"""
Return the position of the first bit set to 1 or 0 in a string.
``start`` and ``end`` difines search range. The range is interpreted
as a range of bytes and not a range of bits, so start=0 and end=2
means to look at the first ... |
Set an expire flag on key name. when can be represented as an integer indicating unix time or a Python datetime object. | def expireat(self, name, when):
"""
Set an expire flag on key ``name``. ``when`` can be represented
as an integer indicating unix time or a Python datetime object.
"""
if isinstance(when, datetime.datetime):
when = int(mod_time.mktime(when.timetuple()))
return... |
Returns a list of values ordered identically to keys | def mget(self, keys, *args):
"""
Returns a list of values ordered identically to ``keys``
"""
args = list_or_args(keys, args)
options = {}
if not args:
options[EMPTY_RESPONSE] = []
return self.execute_command('MGET', *args, **options) |
Sets key/ values based on a mapping. Mapping is a dictionary of key/ value pairs. Both keys and values should be strings or types that can be cast to a string via str (). | def mset(self, mapping):
"""
Sets key/values based on a mapping. Mapping is a dictionary of
key/value pairs. Both keys and values should be strings or types that
can be cast to a string via str().
"""
items = []
for pair in iteritems(mapping):
items.ex... |
Sets key/ values based on a mapping if none of the keys are already set. Mapping is a dictionary of key/ value pairs. Both keys and values should be strings or types that can be cast to a string via str (). Returns a boolean indicating if the operation was successful. | def msetnx(self, mapping):
"""
Sets key/values based on a mapping if none of the keys are already set.
Mapping is a dictionary of key/value pairs. Both keys and values
should be strings or types that can be cast to a string via str().
Returns a boolean indicating if the operation... |
Set an expire flag on key name for time milliseconds. time can be represented by an integer or a Python timedelta object. | def pexpire(self, name, time):
"""
Set an expire flag on key ``name`` for ``time`` milliseconds.
``time`` can be represented by an integer or a Python timedelta
object.
"""
if isinstance(time, datetime.timedelta):
time = int(time.total_seconds() * 1000)
... |
Set an expire flag on key name. when can be represented as an integer representing unix time in milliseconds ( unix time * 1000 ) or a Python datetime object. | def pexpireat(self, name, when):
"""
Set an expire flag on key ``name``. ``when`` can be represented
as an integer representing unix time in milliseconds (unix time * 1000)
or a Python datetime object.
"""
if isinstance(when, datetime.datetime):
ms = int(when.... |
Set the value of key name to value that expires in time_ms milliseconds. time_ms can be represented by an integer or a Python timedelta object | def psetex(self, name, time_ms, value):
"""
Set the value of key ``name`` to ``value`` that expires in ``time_ms``
milliseconds. ``time_ms`` can be represented by an integer or a Python
timedelta object
"""
if isinstance(time_ms, datetime.timedelta):
time_ms =... |
Create a key using the provided serialized value previously obtained using DUMP. | def restore(self, name, ttl, value, replace=False):
"""
Create a key using the provided serialized value, previously obtained
using DUMP.
"""
params = [name, ttl, value]
if replace:
params.append('REPLACE')
return self.execute_command('RESTORE', *param... |
Set the value at key name to value | def set(self, name, value, ex=None, px=None, nx=False, xx=False):
"""
Set the value at key ``name`` to ``value``
``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.
``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.
``nx`` if set to True, set the va... |
Flag the offset in name as value. Returns a boolean indicating the previous value of offset. | def setbit(self, name, offset, value):
"""
Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``.
"""
value = value and 1 or 0
return self.execute_command('SETBIT', name, offset, value) |
Set the value of key name to value that expires in time seconds. time can be represented by an integer or a Python timedelta object. | def setex(self, name, time, value):
"""
Set the value of key ``name`` to ``value`` that expires in ``time``
seconds. ``time`` can be represented by an integer or a Python
timedelta object.
"""
if isinstance(time, datetime.timedelta):
time = int(time.total_seco... |
Overwrite bytes in the value of name starting at offset with value. If offset plus the length of value exceeds the length of the original value the new value will be larger than before. If offset exceeds the length of the original value null bytes will be used to pad between the end of the previous value and the start ... | def setrange(self, name, offset, value):
"""
Overwrite bytes in the value of ``name`` starting at ``offset`` with
``value``. If ``offset`` plus the length of ``value`` exceeds the
length of the original value, the new value will be larger than before.
If ``offset`` exceeds the le... |
LPOP a value off of the first non - empty list named in the keys list. | def blpop(self, keys, timeout=0):
"""
LPOP a value off of the first non-empty list
named in the ``keys`` list.
If none of the lists in ``keys`` has a value to LPOP, then block
for ``timeout`` seconds, or until a value gets pushed on to one
of the lists.
If timeo... |
RPOP a value off of the first non - empty list named in the keys list. | def brpop(self, keys, timeout=0):
"""
RPOP a value off of the first non-empty list
named in the ``keys`` list.
If none of the lists in ``keys`` has a value to RPOP, then block
for ``timeout`` seconds, or until a value gets pushed on to one
of the lists.
If timeo... |
Return a slice of the list name between position start and end | def lrange(self, name, start, end):
"""
Return a slice of the list ``name`` between
position ``start`` and ``end``
``start`` and ``end`` can be negative numbers just like
Python slicing notation
"""
return self.execute_command('LRANGE', name, start, end) |
Remove the first count occurrences of elements equal to value from the list stored at name. | def lrem(self, name, count, value):
"""
Remove the first ``count`` occurrences of elements equal to ``value``
from the list stored at ``name``.
The count argument influences the operation in the following ways:
count > 0: Remove elements equal to value moving from head to ta... |
Set position of list name to value | def lset(self, name, index, value):
"Set ``position`` of list ``name`` to ``value``"
return self.execute_command('LSET', name, index, value) |
Sort and return the list set or sorted set at name. | def sort(self, name, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
"""
Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key... |
Incrementally return lists of key names. Also return a cursor indicating the scan position. | def scan(self, cursor=0, match=None, count=None):
"""
Incrementally return lists of key names. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
piece... |
Make an iterator using the SCAN command so that the client doesn t need to remember the cursor position. | def scan_iter(self, match=None, count=None):
"""
Make an iterator using the SCAN command so that the client doesn't
need to remember the cursor position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
... |
Incrementally return lists of elements in a set. Also return a cursor indicating the scan position. | def sscan(self, name, cursor=0, match=None, count=None):
"""
Incrementally return lists of elements in a set. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
""... |
Incrementally return lists of elements in a sorted set. Also return a cursor indicating the scan position. | def zscan(self, name, cursor=0, match=None, count=None,
score_cast_func=float):
"""
Incrementally return lists of elements in a sorted set. Also return a
cursor indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for h... |
Move value from set src to set dst atomically | def smove(self, src, dst, value):
"Move ``value`` from set ``src`` to set ``dst`` atomically"
return self.execute_command('SMOVE', src, dst, value) |
Remove and return a random member of set name | def spop(self, name, count=None):
"Remove and return a random member of set ``name``"
args = (count is not None) and [count] or []
return self.execute_command('SPOP', name, *args) |
Acknowledges the successful processing of one or more messages. name: name of the stream. groupname: name of the consumer group. * ids: message ids to acknowlege. | def xack(self, name, groupname, *ids):
"""
Acknowledges the successful processing of one or more messages.
name: name of the stream.
groupname: name of the consumer group.
*ids: message ids to acknowlege.
"""
return self.execute_command('XACK', name, groupname, *i... |
Add to a stream. name: name of the stream fields: dict of field/ value pairs to insert into the stream id: Location to insert this record. By default it is appended. maxlen: truncate old stream members beyond this size approximate: actual stream length may be slightly more than maxlen | def xadd(self, name, fields, id='*', maxlen=None, approximate=True):
"""
Add to a stream.
name: name of the stream
fields: dict of field/value pairs to insert into the stream
id: Location to insert this record. By default it is appended.
maxlen: truncate old stream member... |
Changes the ownership of a pending message. name: name of the stream. groupname: name of the consumer group. consumername: name of a consumer that claims the message. min_idle_time: filter messages that were idle less than this amount of milliseconds message_ids: non - empty list or tuple of message IDs to claim idle: ... | def xclaim(self, name, groupname, consumername, min_idle_time, message_ids,
idle=None, time=None, retrycount=None, force=False,
justid=False):
"""
Changes the ownership of a pending message.
name: name of the stream.
groupname: name of the consumer group.
... |
Create a new consumer group associated with a stream. name: name of the stream. groupname: name of the consumer group. id: ID of the last item in the stream to consider already delivered. | def xgroup_create(self, name, groupname, id='$', mkstream=False):
"""
Create a new consumer group associated with a stream.
name: name of the stream.
groupname: name of the consumer group.
id: ID of the last item in the stream to consider already delivered.
"""
pi... |
Remove a specific consumer from a consumer group. Returns the number of pending messages that the consumer had before it was deleted. name: name of the stream. groupname: name of the consumer group. consumername: name of consumer to delete | def xgroup_delconsumer(self, name, groupname, consumername):
"""
Remove a specific consumer from a consumer group.
Returns the number of pending messages that the consumer had before it
was deleted.
name: name of the stream.
groupname: name of the consumer group.
... |
Set the consumer group last delivered ID to something else. name: name of the stream. groupname: name of the consumer group. id: ID of the last item in the stream to consider already delivered. | def xgroup_setid(self, name, groupname, id):
"""
Set the consumer group last delivered ID to something else.
name: name of the stream.
groupname: name of the consumer group.
id: ID of the last item in the stream to consider already delivered.
"""
return self.execu... |
Returns information about pending messages in a range. name: name of the stream. groupname: name of the consumer group. min: minimum stream ID. max: maximum stream ID. count: number of messages to return consumername: name of a consumer to filter by ( optional ). | def xpending_range(self, name, groupname, min, max, count,
consumername=None):
"""
Returns information about pending messages, in a range.
name: name of the stream.
groupname: name of the consumer group.
min: minimum stream ID.
max: maximum stream I... |
Read stream values within an interval. name: name of the stream. start: first stream ID. defaults to - meaning the earliest available. finish: last stream ID. defaults to + meaning the latest available. count: if set only return this many items beginning with the earliest available. | def xrange(self, name, min='-', max='+', count=None):
"""
Read stream values within an interval.
name: name of the stream.
start: first stream ID. defaults to '-',
meaning the earliest available.
finish: last stream ID. defaults to '+',
meaning the ... |
Block and monitor multiple streams for new data. streams: a dict of stream names to stream IDs where IDs indicate the last ID already seen. count: if set only return this many items beginning with the earliest available. block: number of milliseconds to wait if nothing already present. | def xread(self, streams, count=None, block=None):
"""
Block and monitor multiple streams for new data.
streams: a dict of stream names to stream IDs, where
IDs indicate the last ID already seen.
count: if set, only return this many items, beginning with the
... |
Read from a stream via a consumer group. groupname: name of the consumer group. consumername: name of the requesting consumer. streams: a dict of stream names to stream IDs where IDs indicate the last ID already seen. count: if set only return this many items beginning with the earliest available. block: number of mill... | def xreadgroup(self, groupname, consumername, streams, count=None,
block=None, noack=False):
"""
Read from a stream via a consumer group.
groupname: name of the consumer group.
consumername: name of the requesting consumer.
streams: a dict of stream names to st... |
Trims old messages from a stream. name: name of the stream. maxlen: truncate old stream messages beyond this size approximate: actual stream length may be slightly more than maxlen | def xtrim(self, name, maxlen, approximate=True):
"""
Trims old messages from a stream.
name: name of the stream.
maxlen: truncate old stream messages beyond this size
approximate: actual stream length may be slightly more than maxlen
"""
pieces = [Token.get_token(... |
Set any number of element - name score pairs to the key name. Pairs are specified as a dict of element - names keys to score values. | def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False):
"""
Set any number of element-name, score pairs to the key ``name``. Pairs
are specified as a dict of element-names keys to score values.
``nx`` forces ZADD to only create new elements and not to update
sco... |
Returns the number of elements in the sorted set at key name with a score between min and max. | def zcount(self, name, min, max):
"""
Returns the number of elements in the sorted set at key ``name`` with
a score between ``min`` and ``max``.
"""
return self.execute_command('ZCOUNT', name, min, max) |
Increment the score of value in sorted set name by amount | def zincrby(self, name, amount, value):
"Increment the score of ``value`` in sorted set ``name`` by ``amount``"
return self.execute_command('ZINCRBY', name, amount, value) |
Intersect 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. | def zinterstore(self, dest, keys, aggregate=None):
"""
Intersect 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 self._zaggregate('Z... |
Return the number of items in the sorted set name between the lexicographical range min and max. | def zlexcount(self, name, min, max):
"""
Return the number of items in the sorted set ``name`` between the
lexicographical range ``min`` and ``max``.
"""
return self.execute_command('ZLEXCOUNT', name, min, max) |
Remove and return up to count members with the highest scores from the sorted set name. | def zpopmax(self, name, count=None):
"""
Remove and return up to ``count`` members with the highest scores
from the sorted set ``name``.
"""
args = (count is not None) and [count] or []
options = {
'withscores': True
}
return self.execute_comma... |
Remove and return up to count members with the lowest scores from the sorted set name. | def zpopmin(self, name, count=None):
"""
Remove and return up to ``count`` members with the lowest scores
from the sorted set ``name``.
"""
args = (count is not None) and [count] or []
options = {
'withscores': True
}
return self.execute_comman... |
ZPOPMAX a value off of the first non - empty sorted set named in the keys list. | def bzpopmax(self, keys, timeout=0):
"""
ZPOPMAX a value off of the first non-empty sorted set
named in the ``keys`` list.
If none of the sorted sets in ``keys`` has a value to ZPOPMAX,
then block for ``timeout`` seconds, or until a member gets added
to one of the sorted... |
ZPOPMIN a value off of the first non - empty sorted set named in the keys list. | def bzpopmin(self, keys, timeout=0):
"""
ZPOPMIN a value off of the first non-empty sorted set
named in the ``keys`` list.
If none of the sorted sets in ``keys`` has a value to ZPOPMIN,
then block for ``timeout`` seconds, or until a member gets added
to one of the sorted... |
Return the lexicographical range of values from sorted set name between min and max. | def zrangebylex(self, name, min, max, start=None, num=None):
"""
Return the lexicographical range of values from sorted set ``name``
between ``min`` and ``max``.
If ``start`` and ``num`` are specified, then return a slice of the
range.
"""
if (start is not None a... |
Remove all elements in the sorted set name between the lexicographical range specified by min and max. | def zremrangebylex(self, name, min, max):
"""
Remove all elements in the sorted set ``name`` between the
lexicographical range specified by ``min`` and ``max``.
Returns the number of elements removed.
"""
return self.execute_command('ZREMRANGEBYLEX', name, min, max) |
Remove all elements in the sorted set name with ranks between min and max. Values are 0 - based ordered from smallest score to largest. Values can be negative indicating the highest scores. Returns the number of elements removed | def zremrangebyrank(self, name, min, max):
"""
Remove all elements in the sorted set ``name`` with ranks between
``min`` and ``max``. Values are 0-based, ordered from smallest score
to largest. Values can be negative indicating the highest scores.
Returns the number of elements r... |
Return a range of values from the sorted set name with scores between min and max in descending order. | def zrevrangebyscore(self, name, max, min, start=None, num=None,
withscores=False, score_cast_func=float):
"""
Return a range of values from the sorted set ``name`` with scores
between ``min`` and ``max`` in descending order.
If ``start`` and ``num`` are specifi... |
Union 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. | def zunionstore(self, dest, keys, aggregate=None):
"""
Union 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 self._zaggregate('ZUNIO... |
Returns a list of values ordered identically to keys | def hmget(self, name, keys, *args):
"Returns a list of values ordered identically to ``keys``"
args = list_or_args(keys, args)
return self.execute_command('HMGET', name, *args) |
Execute the Lua script specifying the numkeys the script will touch and the key names and argument values in keys_and_args. Returns the result of the script. | def eval(self, script, numkeys, *keys_and_args):
"""
Execute the Lua ``script``, specifying the ``numkeys`` the script
will touch and the key names and argument values in ``keys_and_args``.
Returns the result of the script.
In practice, use the object returned by ``register_scri... |
Use the sha to execute a Lua script already registered via EVAL or SCRIPT LOAD. Specify the numkeys the script will touch and the key names and argument values in keys_and_args. Returns the result of the script. | def evalsha(self, sha, numkeys, *keys_and_args):
"""
Use the ``sha`` to execute a Lua script already registered via EVAL
or SCRIPT LOAD. Specify the ``numkeys`` the script will touch and the
key names and argument values in ``keys_and_args``. Returns the result
of the script.
... |
Add the specified geospatial items to the specified key identified by the name argument. The Geospatial items are given as ordered members of the values argument each item or place is formed by the triad longitude latitude and name. | def geoadd(self, name, *values):
"""
Add the specified geospatial items to the specified key identified
by the ``name`` argument. The Geospatial items are given as ordered
members of the ``values`` argument, each item or place is formed by
the triad longitude, latitude and name.
... |
Return the distance between place1 and place2 members of the name key. The units must be one of the following: m km mi ft. By default meters are used. | def geodist(self, name, place1, place2, unit=None):
"""
Return the distance between ``place1`` and ``place2`` members of the
``name`` key.
The units must be one of the following : m, km mi, ft. By default
meters are used.
"""
pieces = [name, place1, place2]
... |
Re - subscribe to any channels and patterns previously subscribed to | 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 unicode strings
# before passing them to [p]subscribe.
s... |
Parse the response from a publish/ subscribe command | def parse_response(self, block=True, timeout=0):
"Parse 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 psubscri... |
normalize channel/ pattern names to be either bytes or strings based on whether responses are automatically decoded. this saves us from coercing the value for each message coming in. | def _normalize_keys(self, data):
"""
normalize channel/pattern names to be either bytes or strings
based on whether responses are automatically decoded. this saves us
from coercing the value for each message coming in.
"""
encode = self.encoder.encode
decode = sel... |
Subscribe 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 (). | def psubscribe(self, *args, **kwargs):
"""
Subscribe 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... |
Unsubscribe from the supplied patterns. If empty unsubscribe from all patterns. | def punsubscribe(self, *args):
"""
Unsubscribe from the supplied patterns. If empty, unsubscribe from
all patterns.
"""
if args:
args = list_or_args(args[0], args[1:])
patterns = self._normalize_keys(dict.fromkeys(args))
else:
patterns ... |
Subscribe to channels. Channels supplied as keyword arguments expect a channel name as the key and a callable as the value. A channel s callable will be invoked automatically when a message is received on that channel rather than producing a message via listen () or get_message (). | def subscribe(self, *args, **kwargs):
"""
Subscribe to channels. Channels supplied as keyword arguments expect
a channel name as the key and a callable as the value. A channel's
callable will be invoked automatically when a message is received on
that channel rather than producin... |
Unsubscribe from the supplied channels. If empty unsubscribe from all channels | def unsubscribe(self, *args):
"""
Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels
"""
if args:
args = list_or_args(args[0], args[1:])
channels = self._normalize_keys(dict.fromkeys(args))
else:
channels = ... |
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. | 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.
"""
message_type = nativestr(response[... |
Start a transactional block of the pipeline after WATCH commands are issued. End the transactional block with execute. | def multi(self):
"""
Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`.
"""
if self.explicit_transaction:
raise RedisError('Cannot issue nested calls to MULTI')
if self.command_stack:
... |
Stage a command to be executed when execute () is next called | def pipeline_execute_command(self, *args, **options):
"""
Stage a command to be executed when execute() is next called
Returns the current Pipeline object back so commands can be
chained together, such as:
pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
At some ... |
Reset the state of the instance to when it was constructed | def reset(self):
"""
Reset the state of the instance to when it was constructed
"""
self.operations = []
self._last_overflow = 'WRAP'
self.overflow(self._default_overflow or self._last_overflow) |
Update the overflow algorithm of successive INCRBY operations: param overflow: Overflow algorithm one of WRAP SAT FAIL. See the Redis docs for descriptions of these algorithmsself.: returns: a: py: class: BitFieldOperation instance. | def overflow(self, overflow):
"""
Update the overflow algorithm of successive INCRBY operations
:param overflow: Overflow algorithm, one of WRAP, SAT, FAIL. See the
Redis docs for descriptions of these algorithmsself.
:returns: a :py:class:`BitFieldOperation` instance.
... |
Get the value of a given bitfield.: param fmt: format - string for the bitfield being read e. g. u8 for an unsigned 8 - bit integer.: param offset: offset ( in number of bits ). If prefixed with a # this is an offset multiplier e. g. given the arguments fmt = u8 offset = #2 the offset will be 16.: returns: a: py: class... | def get(self, fmt, offset):
"""
Get the value of a given bitfield.
:param fmt: format-string for the bitfield being read, e.g. 'u8' for
an unsigned 8-bit integer.
:param offset: offset (in number of bits). If prefixed with a
'#', this is an offset multiplier, e.g.... |
Set the value of a given bitfield.: param fmt: format - string for the bitfield being read e. g. u8 for an unsigned 8 - bit integer.: param offset: offset ( in number of bits ). If prefixed with a # this is an offset multiplier e. g. given the arguments fmt = u8 offset = #2 the offset will be 16.: param int value: valu... | def set(self, fmt, offset, value):
"""
Set the value of a given bitfield.
:param fmt: format-string for the bitfield being read, e.g. 'u8' for
an unsigned 8-bit integer.
:param offset: offset (in number of bits). If prefixed with a
'#', this is an offset multiplie... |
Execute the operation ( s ) in a single BITFIELD command. The return value is a list of values corresponding to each operation. If the client used to create this instance was a pipeline the list of values will be present within the pipeline s execute. | def execute(self):
"""
Execute the operation(s) in a single BITFIELD command. The return value
is a list of values corresponding to each operation. If the client
used to create this instance was a pipeline, the list of values
will be present within the pipeline's execute.
... |
Gets a cached token object or creates a new one if not already cached | def get_token(cls, value):
"Gets a cached token object or creates a new one if not already cached"
# Use try/except because after running for a short time most tokens
# should already be cached
try:
return cls._cache[value]
except KeyError:
token = Token(... |
Return a bytestring representation of the value | def encode(self, value):
"Return a bytestring representation of the value"
if isinstance(value, Token):
return value.encoded_value
elif isinstance(value, bytes):
return value
elif isinstance(value, bool):
# special case bool since it is a subclass of i... |
Return a unicode string from the byte representation | def decode(self, value, force=False):
"Return a unicode string from the byte representation"
if (self.decode_responses or force) and isinstance(value, bytes):
value = value.decode(self.encoding, self.encoding_errors)
return value |
Parse an error response | def parse_error(self, response):
"Parse an error response"
error_code = response.split(' ')[0]
if error_code in self.EXCEPTION_CLASSES:
response = response[len(error_code) + 1:]
exception_class = self.EXCEPTION_CLASSES[error_code]
if isinstance(exception_class... |
Called when the socket connects | def on_connect(self, connection):
"Called when the socket connects"
self._sock = connection._sock
self._buffer = SocketBuffer(self._sock, self.socket_read_size)
self.encoder = connection.encoder |
Called when the socket disconnects | def on_disconnect(self):
"Called when the socket disconnects"
self._sock = None
if self._buffer is not None:
self._buffer.close()
self._buffer = None
self.encoder = None |
Connects to the Redis server if not already connected | def connect(self):
"Connects to the Redis server if not already connected"
if self._sock:
return
try:
sock = self._connect()
except socket.timeout:
raise TimeoutError("Timeout connecting to server")
except socket.error:
e = sys.exc_... |
Disconnects from the Redis server | def disconnect(self):
"Disconnects from the Redis server"
self._parser.on_disconnect()
if self._sock is None:
return
if self._selector is not None:
self._selector.close()
self._selector = None
try:
if os.getpid() == self.pid:
... |
Send an already packed command to the Redis server | def send_packed_command(self, command):
"Send an already packed command to the Redis server"
if not self._sock:
self.connect()
try:
if isinstance(command, str):
command = [command]
for item in command:
self._sock.sendall(item)
... |
Poll the socket to see if there s data that can be read. | def can_read(self, timeout=0):
"Poll the socket to see if there's data that can be read."
sock = self._sock
if not sock:
self.connect()
sock = self._sock
return self._parser.can_read() or self._selector.can_read(timeout) |
Read the response from a previously sent command | def read_response(self):
"Read the response from a previously sent command"
try:
response = self._parser.read_response()
except socket.timeout:
self.disconnect()
raise TimeoutError("Timeout reading from %s:%s" %
(self.host, self.... |
Pack a series of arguments into the Redis protocol | def pack_command(self, *args):
"Pack a series of arguments into the Redis protocol"
output = []
# the client might have included 1 or more literal arguments in
# the command name, e.g., 'CONFIG GET'. The Redis server expects these
# arguments to be sent separately, so split the f... |
Wrap the socket with SSL support | def _connect(self):
"Wrap the socket with SSL support"
sock = super(SSLConnection, self)._connect()
if hasattr(ssl, "create_default_context"):
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = self.cert_reqs
... |
Create a Unix domain socket connection | def _connect(self):
"Create a Unix domain socket connection"
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(self.socket_timeout)
sock.connect(self.path)
return sock |
Return a connection pool configured from the given URL. | def from_url(cls, url, db=None, decode_components=False, **kwargs):
"""
Return a connection pool configured from the given URL.
For example::
redis://[:password]@localhost:6379/0
rediss://[:password]@localhost:6379/0
unix://[:password]@/path/to/socket.sock?d... |
Get a connection from the pool | def get_connection(self, command_name, *keys, **options):
"Get a connection from the pool"
self._checkpid()
try:
connection = self._available_connections.pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection)
... |
Return an encoder based on encoding settings | def get_encoder(self):
"Return an encoder based on encoding settings"
kwargs = self.connection_kwargs
return Encoder(
encoding=kwargs.get('encoding', 'utf-8'),
encoding_errors=kwargs.get('encoding_errors', 'strict'),
decode_responses=kwargs.get('decode_respons... |
Create a new connection | def make_connection(self):
"Create a new connection"
if self._created_connections >= self.max_connections:
raise ConnectionError("Too many connections")
self._created_connections += 1
return self.connection_class(**self.connection_kwargs) |
Disconnects all connections in the pool | def disconnect(self):
"Disconnects all connections in the pool"
self._checkpid()
all_conns = chain(self._available_connections,
self._in_use_connections)
for connection in all_conns:
connection.disconnect() |
Make a fresh connection. | def make_connection(self):
"Make a fresh connection."
connection = self.connection_class(**self.connection_kwargs)
self._connections.append(connection)
return connection |
Get a connection blocking for self. timeout until a connection is available from the pool. | def get_connection(self, command_name, *keys, **options):
"""
Get a connection, blocking for ``self.timeout`` until a connection
is available from the pool.
If the connection returned is ``None`` then creates a new connection.
Because we use a last-in first-out queue, the existi... |
Releases the connection back to the pool. | def release(self, connection):
"Releases the connection back to the pool."
# Make sure we haven't changed process.
self._checkpid()
if connection.pid != self.pid:
return
# Put the connection back into the pool.
try:
self.pool.put_nowait(connection... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.