text
stringlengths
81
112k
Return low-level information about an exec command. Args: exec_id (str): ID of the exec instance Returns: (dict): Dictionary of values returned by the endpoint. Raises: :py:class:`docker.errors.APIError` If the server returns an error. def ...
Resize the tty session used by the specified exec command. Args: exec_id (str): ID of the exec instance height (int): Height of tty session width (int): Width of tty session def exec_resize(self, exec_id, height=None, width=None): """ Resize the tty session ...
Start a previously set up exec instance. Args: exec_id (str): ID of the exec instance detach (bool): If true, detach from the exec command. Default: False tty (bool): Allocate a pseudo-TTY. Default: False stream (bool): Stream response data. Defau...
Raises stored :class:`APIError`, if one occurred. def _raise_for_status(self, response): """Raises stored :class:`APIError`, if one occurred.""" try: response.raise_for_status() except requests.exceptions.HTTPError as e: raise create_api_error_from_http_exception(e)
Generator for data coming from a chunked-encoded HTTP response. def _stream_helper(self, response, decode=False): """Generator for data coming from a chunked-encoded HTTP response.""" if response.raw._fp.chunked: if decode: for chunk in json_stream(self._stream_helper(respo...
A generator of multiplexed data blocks read from a buffered response. def _multiplexed_buffer_helper(self, response): """A generator of multiplexed data blocks read from a buffered response.""" buf = self._result(response, binary=True) buf_length = len(buf) walker = 0 ...
A generator of multiplexed data blocks coming from a response stream. def _multiplexed_response_stream_helper(self, response): """A generator of multiplexed data blocks coming from a response stream.""" # Disable timeout on the underlying socket to prevent # Read timed out(s) f...
Stream result for TTY-enabled container and raw binary data def _stream_raw_result(self, response, chunk_size=1, decode=True): ''' Stream result for TTY-enabled container and raw binary data''' self._raise_for_status(response) for out in response.iter_content(chunk_size, decode): yi...
Depending on the combination of python version and whether we're connecting over http or https, we might need to access _sock, which may or may not exist; or we may need to just settimeout on socket itself, which also may or may not have settimeout on it. To avoid missing the correct one...
Force a reload of the auth configuration Args: dockercfg_path (str): Use a custom path for the Docker config file (default ``$HOME/.docker/config.json`` if present, otherwise``$HOME/.dockercfg``) Returns: None def reload_config(self, dockercfg_p...
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 ...
Returns True if this key is locked by this lock, otherwise False. def owned(self): """ Returns True if this key is locked by this lock, otherwise False. """ stored_token = self.redis.get(self.name) # need to always compare bytes to bytes # TODO: this can be simplified wh...
Resets a TTL of an already acquired lock back to a timeout value. def reacquire(self): """ Resets a TTL of an already acquired lock back to a timeout value. """ if self.local.token is None: raise LockError("Cannot reacquire an unlocked lock") if self.timeout is None:...
Converts a unix timestamp to a Python datetime object def timestamp_to_datetime(response): "Converts a unix timestamp to a Python datetime object" if not response: return None try: response = int(response) except ValueError: return None return datetime.datetime.fromtimestamp...
Create a dict given a list of key/value pairs def pairs_to_dict(response, decode_keys=False): "Create a dict given a list of key/value pairs" if response is None: return {} if decode_keys: # the iter form is faster, but I don't know how to make that work # with a nativestr() map ...
If ``withscores`` is specified in the options, return the response as a list of (value, score) pairs 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.get('withsc...
If ``groups`` is specified, return the response as a list of n-element tuples with n being the value found in options['groups'] def sort_return_tuples(response, **options): """ If ``groups`` is specified, return the response as a list of n-element tuples with n being the value found in options['groups'...
Return a Redis client object configured from the given URL For example:: redis://[:password]@localhost:6379/0 rediss://[:password]@localhost:6379/0 unix://[:password]@/path/to/socket.sock?db=0 Three URL schemes are supported: - ```redis://`` <htt...
Return a new Lock object using key ``name`` that mimics the behavior of threading.Lock. If specified, ``timeout`` indicates a maximum life for the lock. By default, it will remain locked until release() is called. ``sleep`` indicates the amount of time to sleep per loop iteration ...
Execute a command and return a parsed response def execute_command(self, *args, **options): "Execute a command and return a parsed response" pool = self.connection_pool command_name = args[0] connection = pool.get_connection(command_name, **options) try: connection.s...
Parses a response from the Redis server def parse_response(self, connection, command_name, **options): "Parses a response from the Redis server" try: response = connection.read_response() except ResponseError: if EMPTY_RESPONSE in options: return options[...
Disconnects client(s) using a variety of filter options :param id: Kills a client by its unique ID field :param type: Kills a client by type where type is one of 'normal', 'master', 'slave' or 'pubsub' :param addr: Kills a client by its 'address:port' :param skipme: If True, then...
Returns a list of currently connected clients. If type of client specified, only that type will be returned. :param _type: optional. one of the client types (normal, master, replica, pubsub) def client_list(self, _type=None): """ Returns a list of currently connected clients. ...
Unblocks a connection by its client id. If ``error`` is True, unblocks the client with a special error message. If ``error`` is False (default), the client is unblocked using the regular timeout mechanism. def client_unblock(self, client_id, error=False): """ Unblocks a connecti...
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 isins...
Delete all keys in all databases on the current host. ``asynchronous`` indicates whether the operation is executed asynchronously by the server. def flushall(self, asynchronous=False): """ Delete all keys in all databases on the current host. ``asynchronous`` indicates whether...
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 milliseconds, indicates the maximum time the connection between the two servers can be idle before the command is interrup...
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. 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 all elements. def memory_usage(self, key, samples=None)...
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...
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 ...
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_comm...
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): ...
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 obj...
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.e...
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. Bo...
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): ...
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 P...
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...
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`` milli...
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:...
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 value at key ``name`` to ``value`` only if it does not exist. ``xx`...
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 ...
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 ...
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 t...
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 timeout is 0, then block indefinitely. def blpop(self, key...
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 timeout is 0, then block indefinitely. def brpop(self, key...
Return a slice of the list ``name`` between position ``start`` and ``end`` ``start`` and ``end`` can be negative numbers just like Python slicing notation def lrange(self, name, start, end): """ Return a slice of the list ``name`` between position ``start`` and ``end`` ...
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 tail. count < 0: Remove elements equal to valu...
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``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight and sort the items. Use an "*" to indicate where in the key the item value is located ``get`` allows for returning ...
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 def scan(self, cursor=0, match=None, count=None): """ Incrementally return lis...
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 def scan_iter(self, match=None, count=None): """ Make an iterator...
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 def sscan(self, name, cursor=0, match=None, count=None): """ Increment...
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 hint the minimum number of returns ``score_cast_func`` a callable used to cast the score return value def...
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. na...
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 ma...
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-empt...
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...
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, grou...
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 delivere...
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 xpen...
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, begi...
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,...
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 ...
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. nam...
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 scores for elements that already exist. ``xx`` forces ZADD to only update scores of ele...
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.exe...
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 `...
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 s...
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 [co...
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 [coun...
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 sets. If timeout is 0, then block indefinitely....
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 sets. If timeout is 0, then block indefinitely....
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. def zrangebylex(self, name, min, max, start=None, num=None): """ Return the lexicographical range of values...
Remove all elements in the sorted set ``name`` between the lexicographical range specified by ``min`` and ``max``. Returns the number of elements removed. def zremrangebylex(self, name, min, max): """ Remove all elements in the sorted set ``name`` between the lexicographical ra...
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): """ ...
Return a range of values from the sorted set ``name`` with scores between ``min`` and ``max`` in descending order. If ``start`` and ``num`` are specified, then return a slice of the range. ``withscores`` indicates to return the scores along with the values. The return type is a...
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`` ...
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. In practice, use the object returned by ``register_script``. This function exists purely for Redis API completion. ...
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. In practice, use the object returned by ``register_script``. Th...
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): """ ...
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`` mem...
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 unic...
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: ' ...
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 ...
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 psubscr...
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:]) ...
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()``....
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:]) c...
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 w...
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 s...
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 other point, you can then run: pipe.execute(), which will execute ...
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): """ Updat...
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', offse...