Backends¶
-
class
redisdb.backends.RedisRing(location, params)[source]¶ RedisRing backend which writes only to one Redis server based on key.
RedisRing is only a proxy to underlying
ConstRedisobjects, which represents each Redis instance. It has the same methods set asConstRedis. Individual nodes can be accessed through nodes attribute.RedisRing is better suited for using Redis as memcached replacement. With one server failure data kept on that server have to be recreated.
-
class
redisdb.backends.RedisCopy(location, params)[source]¶ Redis backend which writes to all Redis servers.
RedisCopy is only a proxy to underlying
ConstRedisobjects, which represents each Redis instance. It has the same methods set asConstRedis. Individual nodes can be accessed through nodes attribute.Fetching is done only from one server based on key just like in RedisRing. RedisCopy can be seen like master/master configuration where synchronization isn’t done by Redis itself but by clients. It’s well suited for storing data that should be available even if one server goes down.
-
class
redisdb.backends.ConstRedis(*args, **kwargs)[source]¶ Redis client that adds consistent hashing to
StrictRedis.-
append(key, value)¶ Appends the string
valueto the value atkey. Ifkeydoesn’t already exist, create it with a value ofvalue. Returns the new length of the value atkey.
-
bgrewriteaof()¶ Tell the Redis server to rewrite the AOF file from data in memory.
-
bgsave()¶ Tell the Redis server to save its data to disk. Unlike save(), this method is asynchronous and returns immediately.
-
bitcount(key, start=None, end=None)¶ Returns the count of set bits in the value of
key. Optionalstartandendparamaters indicate which bytes to consider
-
bitop(operation, dest, *keys)¶ Perform a bitwise operation using
operationbetweenkeysand store the result indest.
-
bitpos(key, bit, start=None, end=None)¶ Return the position of the first bit set to 1 or 0 in a string.
startandenddifines 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.
-
blpop(keys, timeout=0)¶ LPOP a value off of the first non-empty list named in the
keyslist.If none of the lists in
keyshas a value to LPOP, then block fortimeoutseconds, or until a value gets pushed on to one of the lists.If timeout is 0, then block indefinitely.
-
brpop(keys, timeout=0)¶ RPOP a value off of the first non-empty list named in the
keyslist.If none of the lists in
keyshas a value to LPOP, then block fortimeoutseconds, or until a value gets pushed on to one of the lists.If timeout is 0, then block indefinitely.
-
brpoplpush(src, dst, timeout=0)¶ Pop a value off the tail of
src, push it on the head ofdstand then return it.This command blocks until a value is in
srcor untiltimeoutseconds elapse, whichever is first. Atimeoutvalue of 0 blocks forever.
-
client_getname()¶ Returns the current connection name
-
client_kill(address)¶ Disconnects the client at
address(ip:port)
-
client_list()¶ Returns a list of currently connected clients
-
client_setname(name)¶ Sets the current connection name
-
config_get(pattern='*')¶ Return a dictionary of configuration based on the
pattern
-
config_resetstat()¶ Reset runtime statistics
-
config_rewrite()¶ Rewrite config file with the minimal change to reflect running config
-
config_set(name, value)¶ Set config item
namewithvalue
-
dbsize()¶ Returns the number of keys in the current database
-
debug_object(key)¶ Returns version specific meta information about a given key
-
decr(name, amount=1)¶ Decrements the value of
keybyamount. If no key exists, the value will be initialized as 0 -amount
-
delete(*names)¶ Delete one or more keys specified by
names
-
dump(name)¶ Return a serialized version of the value stored at the specified key. If key does not exist a nil bulk reply is returned.
-
echo(value)¶ Echo the string back from the server
-
eval(script, numkeys, *keys_and_args)¶ Execute the Lua
script, specifying thenumkeysthe script will touch and the key names and argument values inkeys_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.
-
evalsha(sha, numkeys, *keys_and_args)¶ Use the
shato execute a Lua script already registered via EVAL or SCRIPT LOAD. Specify thenumkeysthe script will touch and the key names and argument values inkeys_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.
-
execute_command(*args, **options)¶ Execute a command and return a parsed response
-
exists(name)¶ Returns a boolean indicating whether key
nameexists
-
expire(name, time)¶ Set an expire flag on key
namefortimeseconds.timecan be represented by an integer or a Python timedelta object.
-
expireat(name, when)¶ Set an expire flag on key
name.whencan be represented as an integer indicating unix time or a Python datetime object.
-
flushall()¶ Delete all keys in all databases on the current host
-
flushdb()¶ Delete all keys in the current database
-
from_url(url, db=None, **kwargs)¶ Return a Redis client object configured from the given URL.
For example:
redis://[:password]@localhost:6379/0 unix://[:password]@/path/to/socket.sock?db=0
There are several ways to specify a database number. The parse function will return the first specified option:
- A
dbquerystring option, e.g. redis://localhost?db=0 - If using the redis:// scheme, the path argument of the url, e.g. redis://localhost/0
- The
dbargument to this function.
If none of these options are specified, db=0 is used.
Any additional querystring arguments and keyword arguments will be passed along to the ConnectionPool class’s initializer. In the case of conflicting arguments, querystring arguments always win.
- A
-
get(name)¶ Return the value at key
name, or None if the key doesn’t exist
-
getbit(name, offset)¶ Returns a boolean indicating the value of
offsetinname
-
getrange(key, start, end)¶ Returns the substring of the string value stored at
key, determined by the offsetsstartandend(both are inclusive)
-
getset(name, value)¶ Sets the value at key
nametovalueand returns the old value at keynameatomically.
-
hdel(name, *keys)¶ Delete
keysfrom hashname
-
hexists(name, key)¶ Returns a boolean indicating if
keyexists within hashname
-
hget(name, key)¶ Return the value of
keywithin the hashname
-
hgetall(name)¶ Return a Python dict of the hash’s name/value pairs
-
hincrby(name, key, amount=1)¶ Increment the value of
keyin hashnamebyamount
-
hincrbyfloat(name, key, amount=1.0)¶ Increment the value of
keyin hashnameby floatingamount
-
hkeys(name)¶ Return the list of keys within hash
name
-
hlen(name)¶ Return the number of elements in hash
name
-
hmget(name, keys, *args)¶ Returns a list of values ordered identically to
keys
-
hmset(name, mapping)¶ Set key to value within hash
namefor each corresponding key and value from themappingdict.
-
hscan(name, cursor=0, match=None, count=None)¶ Incrementally return key/value slices in a hash. Also return a cursor indicating the scan position.
matchallows for filtering the keys by patterncountallows for hint the minimum number of returns
-
hscan_iter(name, match=None, count=None)¶ Make an iterator using the HSCAN command so that the client doesn’t need to remember the cursor position.
matchallows for filtering the keys by patterncountallows for hint the minimum number of returns
-
hset(name, key, value)¶ Set
keytovaluewithin hashnameReturns 1 if HSET created a new field, otherwise 0
-
hsetnx(name, key, value)¶ Set
keytovaluewithin hashnameifkeydoes not exist. Returns 1 if HSETNX created a field, otherwise 0.
-
hvals(name)¶ Return the list of values within hash
name
-
incr(name, amount=1)¶ Increments the value of
keybyamount. If no key exists, the value will be initialized asamount
-
incrby(name, amount=1)¶ Increments the value of
keybyamount. If no key exists, the value will be initialized asamount
-
incrbyfloat(name, amount=1.0)¶ Increments the value at key
nameby floatingamount. If no key exists, the value will be initialized asamount
-
info(section=None)¶ Returns a dictionary containing information about the Redis server
The
sectionoption can be used to select a specific section of informationThe section option is not supported by older versions of Redis Server, and will generate ResponseError
-
keys(pattern='*')¶ Returns a list of keys matching
pattern
-
lastsave()¶ Return a Python datetime object representing the last time the Redis database was saved to disk
-
lindex(name, index)¶ Return the item from list
nameat positionindexNegative indexes are supported and will return an item at the end of the list
-
linsert(name, where, refvalue, value)¶ Insert
valuein listnameeither immediately before or after [where]refvalueReturns the new length of the list on success or -1 if
refvalueis not in the list.
-
llen(name)¶ Return the length of the list
name
-
lock(name, timeout=None, sleep=0.1, blocking_timeout=None, lock_class=None, thread_local=True)¶ Return a new Lock object using key
namethat mimics the behavior of threading.Lock.If specified,
timeoutindicates a maximum life for the lock. By default, it will remain locked until release() is called.sleepindicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock.blocking_timeoutindicates the maximum amount of time in seconds to spend trying to acquire the lock. A value ofNoneindicates continue trying forever.blocking_timeoutcan be specified as a float or integer, both representing the number of seconds to wait.lock_classforces the specified lock implementation.thread_localindicates whether the lock token is placed in thread-local storage. By default, the token is placed in thread local storage so that a thread only sees its token, not a token set by another thread. Consider the following timeline:- time: 0, thread-1 acquires my-lock, with a timeout of 5 seconds.
- thread-1 sets the token to “abc”
- time: 1, thread-2 blocks trying to acquire my-lock using the
- Lock instance.
- time: 5, thread-1 has not yet completed. redis expires the lock
- key.
- time: 5, thread-2 acquired my-lock now that it’s available.
- thread-2 sets the token to “xyz”
- time: 6, thread-1 finishes its work and calls release(). if the
- token is not stored in thread local storage, then thread-1 would see the token value as “xyz” and would be able to successfully release the thread-2’s lock.
In some use cases it’s necessary to disable thread local storage. For example, if you have code where one thread acquires a lock and passes that lock instance to a worker thread to release later. If thread local storage isn’t disabled in this case, the worker thread won’t see the token set by the thread that acquired the lock. Our assumption is that these cases aren’t common and as such default to using thread local storage.
-
lpop(name)¶ Remove and return the first item of the list
name
-
lpush(name, *values)¶ Push
valuesonto the head of the listname
-
lpushx(name, value)¶ Push
valueonto the head of the listnameifnameexists
-
lrange(name, start, end)¶ Return a slice of the list
namebetween positionstartandendstartandendcan be negative numbers just like Python slicing notation
-
lrem(name, count, value)¶ Remove the first
countoccurrences of elements equal tovaluefrom the list stored atname.- 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 value moving from tail to head. count = 0: Remove all elements equal to value.
-
lset(name, index, value)¶ Set
positionof listnametovalue
-
ltrim(name, start, end)¶ Trim the list
name, removing all values not within the slice betweenstartandendstartandendcan be negative numbers just like Python slicing notation
-
mget(keys, *args)¶ Returns a list of values ordered identically to
keys
-
move(name, db)¶ Moves the key
nameto a different Redis databasedb
-
mset(*args, **kwargs)¶ Sets key/values based on a mapping. Mapping can be supplied as a single dictionary argument or as kwargs.
-
msetnx(*args, **kwargs)¶ Sets key/values based on a mapping if none of the keys are already set. Mapping can be supplied as a single dictionary argument or as kwargs. Returns a boolean indicating if the operation was successful.
-
object(infotype, key)¶ Return the encoding, idletime, or refcount about the key
-
parse_response(connection, command_name, **options)¶ Parses a response from the Redis server
-
persist(name)¶ Removes an expiration on
name
-
pexpire(name, time)¶ Set an expire flag on key
namefortimemilliseconds.timecan be represented by an integer or a Python timedelta object.
-
pexpireat(name, when)¶ Set an expire flag on key
name.whencan be represented as an integer representing unix time in milliseconds (unix time * 1000) or a Python datetime object.
-
pfadd(name, *values)¶ Adds the specified elements to the specified HyperLogLog.
-
pfcount(name)¶ Return the approximated cardinality of the set observed by the HyperLogLog at key.
-
pfmerge(dest, *sources)¶ Merge N different HyperLogLogs into a single one.
-
ping()¶ Ping the Redis server
-
pipeline(transaction=True, shard_hint=None)¶ Return a new pipeline object that can queue multiple commands for later execution.
transactionindicates whether all commands should be executed atomically. Apart from making a group of operations atomic, pipelines are useful for reducing the back-and-forth overhead between the client and server.
-
psetex(name, time_ms, value)¶ Set the value of key
nametovaluethat expires intime_msmilliseconds.time_mscan be represented by an integer or a Python timedelta object
-
pttl(name)¶ Returns the number of milliseconds until the key
namewill expire
-
publish(channel, message)¶ Publish
messageonchannel. Returns the number of subscribers the message was delivered to.
-
pubsub(**kwargs)¶ Return a Publish/Subscribe object. With this object, you can subscribe to channels and listen for messages that get published to them.
-
randomkey()¶ Returns the name of a random key
-
register_script(script)¶ Register a Lua
scriptspecifying thekeysit will touch. Returns a Script object that is callable and hides the complexity of deal with scripts, keys, and shas. This is the preferred way to work with Lua scripts.
-
rename(src, dst)¶ Rename key
srctodst
-
renamenx(src, dst)¶ Rename key
srctodstifdstdoesn’t already exist
-
restore(name, ttl, value)¶ Create a key using the provided serialized value, previously obtained using DUMP.
-
rpop(name)¶ Remove and return the last item of the list
name
-
rpoplpush(src, dst)¶ RPOP a value off of the
srclist and atomically LPUSH it on to thedstlist. Returns the value.
-
rpush(name, *values)¶ Push
valuesonto the tail of the listname
-
rpushx(name, value)¶ Push
valueonto the tail of the listnameifnameexists
-
sadd(name, *values)¶ Add
value(s)to setname
-
save()¶ Tell the Redis server to save its data to disk, blocking until the save is complete
-
scan(cursor=0, match=None, count=None)¶ Incrementally return lists of key names. Also return a cursor indicating the scan position.
matchallows for filtering the keys by patterncountallows for hint the minimum number of returns
-
scan_iter(match=None, count=None)¶ Make an iterator using the SCAN command so that the client doesn’t need to remember the cursor position.
matchallows for filtering the keys by patterncountallows for hint the minimum number of returns
-
scard(name)¶ Return the number of elements in set
name
-
script_exists(*args)¶ Check if a script exists in the script cache by specifying the SHAs of each script as
args. Returns a list of boolean values indicating if if each already script exists in the cache.
-
script_flush()¶ Flush all scripts from the script cache
-
script_kill()¶ Kill the currently executing Lua script
-
script_load(script)¶ Load a Lua
scriptinto the script cache. Returns the SHA.
-
sdiff(keys, *args)¶ Return the difference of sets specified by
keys
-
sdiffstore(dest, keys, *args)¶ Store the difference of sets specified by
keysinto a new set nameddest. Returns the number of keys in the new set.
-
sentinel(*args)¶ Redis Sentinel’s SENTINEL command.
-
sentinel_get_master_addr_by_name(service_name)¶ Returns a (host, port) pair for the given
service_name
-
sentinel_master(service_name)¶ Returns a dictionary containing the specified masters state.
-
sentinel_masters()¶ Returns a list of dictionaries containing each master’s state.
-
sentinel_monitor(name, ip, port, quorum)¶ Add a new master to Sentinel to be monitored
-
sentinel_remove(name)¶ Remove a master from Sentinel’s monitoring
-
sentinel_sentinels(service_name)¶ Returns a list of sentinels for
service_name
-
sentinel_set(name, option, value)¶ Set Sentinel monitoring parameters for a given master
-
sentinel_slaves(service_name)¶ Returns a list of slaves for
service_name
-
set(name, value, ex=None, px=None, nx=False, xx=False)¶ Set the value at key
nametovalueexsets an expire flag on keynameforexseconds.pxsets an expire flag on keynameforpxmilliseconds.nxif set to True, set the value at keynametovalueif it- does not already exist.
xxif set to True, set the value at keynametovalueif it- already exists.
-
set_response_callback(command, callback)¶ Set a custom Response Callback
-
setbit(name, offset, value)¶ Flag the
offsetinnameasvalue. Returns a boolean indicating the previous value ofoffset.
-
setex(name, time, value)¶ Set the value of key
nametovaluethat expires intimeseconds.timecan be represented by an integer or a Python timedelta object.
-
setnx(name, value)¶ Set the value of key
nametovalueif key doesn’t exist
-
setrange(name, offset, value)¶ Overwrite bytes in the value of
namestarting atoffsetwithvalue. Ifoffsetplus the length ofvalueexceeds the length of the original value, the new value will be larger than before. Ifoffsetexceeds the length of the original value, null bytes will be used to pad between the end of the previous value and the start of what’s being injected.Returns the length of the new string.
-
shutdown()¶ Shutdown the server
-
sinter(keys, *args)¶ Return the intersection of sets specified by
keys
-
sinterstore(dest, keys, *args)¶ Store the intersection of sets specified by
keysinto a new set nameddest. Returns the number of keys in the new set.
-
sismember(name, value)¶ Return a boolean indicating if
valueis a member of setname
-
slaveof(host=None, port=None)¶ Set the server to be a replicated slave of the instance identified by the
hostandport. If called without arguments, the instance is promoted to a master instead.
-
slowlog_get(num=None)¶ Get the entries from the slowlog. If
numis specified, get the most recentnumitems.
-
slowlog_len()¶ Get the number of items in the slowlog
-
slowlog_reset()¶ Remove all items in the slowlog
-
smembers(name)¶ Return all members of the set
name
-
smove(src, dst, value)¶ Move
valuefrom setsrcto setdstatomically
-
sort(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.startandnumallow for paging through the sorted databyallows using an external key to weight and sort the items.- Use an “*” to indicate where in the key the item value is located
getallows for returning items from external keys rather than the- sorted data itself. Use an “*” to indicate where int he key the item value is located
descallows for reversing the sortalphaallows for sorting lexicographically rather than numericallystoreallows for storing the result of the sort into- the key
store groupsif set to True and ifgetcontains at least two- elements, sort will return a list of tuples, each containing the
values fetched from the arguments to
get.
-
spop(name)¶ Remove and return a random member of set
name
-
srandmember(name, number=None)¶ If
numberis None, returns a random member of setname.If
numberis supplied, returns a list ofnumberrandom memebers of setname. Note this is only available when running Redis 2.6+.
-
srem(name, *values)¶ Remove
valuesfrom setname
-
sscan(name, cursor=0, match=None, count=None)¶ Incrementally return lists of elements in a set. Also return a cursor indicating the scan position.
matchallows for filtering the keys by patterncountallows for hint the minimum number of returns
-
sscan_iter(name, match=None, count=None)¶ Make an iterator using the SSCAN command so that the client doesn’t need to remember the cursor position.
matchallows for filtering the keys by patterncountallows for hint the minimum number of returns
-
strlen(name)¶ Return the number of bytes stored in the value of
name
-
substr(name, start, end=-1)¶ Return a substring of the string at key
name.startandendare 0-based integers specifying the portion of the string to return.
-
sunion(keys, *args)¶ Return the union of sets specified by
keys
-
sunionstore(dest, keys, *args)¶ Store the union of sets specified by
keysinto a new set nameddest. Returns the number of keys in the new set.
-
time()¶ Returns the server time as a 2-item tuple of ints: (seconds since epoch, microseconds into this second).
-
transaction(func, *watches, **kwargs)¶ Convenience method for executing the callable func as a transaction while watching all keys specified in watches. The ‘func’ callable should expect a single argument which is a Pipeline object.
-
ttl(name)¶ Returns the number of seconds until the key
namewill expire
-
type(name)¶ Returns the type of key
name
-
unwatch()¶ Unwatches the value at key
name, or None of the key doesn’t exist
-
watch(*names)¶ Watches the values at keys
names, or None if the key doesn’t exist
-
zadd(name, *args, **kwargs)¶ Set any number of score, element-name pairs to the key
name. Pairs can be specified in two ways:As *args, in the form of: score1, name1, score2, name2, ... or as **kwargs, in the form of: name1=score1, name2=score2, ...
The following example would add four values to the ‘my-key’ key: redis.zadd(‘my-key’, 1.1, ‘name1’, 2.2, ‘name2’, name3=3.3, name4=4.4)
-
zcard(name)¶ Return the number of elements in the sorted set
name
-
zcount(name, min, max)¶ Returns the number of elements in the sorted set at key
namewith a score betweenminandmax.
-
zincrby(name, value, amount=1)¶ Increment the score of
valuein sorted setnamebyamount
-
zinterstore(dest, keys, aggregate=None)¶ Intersect multiple sorted sets specified by
keysinto a new sorted set,dest. Scores in the destination will be aggregated based on theaggregate, or SUM if none is provided.
-
zlexcount(name, min, max)¶ Return the number of items in the sorted set
namebetween the lexicographical rangeminandmax.
-
zrange(name, start, end, desc=False, withscores=False, score_cast_func=<type 'float'>)¶ Return a range of values from sorted set
namebetweenstartandendsorted in ascending order.startandendcan be negative, indicating the end of the range.desca boolean indicating whether to sort the results descendinglywithscoresindicates to return the scores along with the values. The return type is a list of (value, score) pairsscore_cast_funca callable used to cast the score return value
-
zrangebylex(name, min, max, start=None, num=None)¶ Return the lexicographical range of values from sorted set
namebetweenminandmax.If
startandnumare specified, then return a slice of the range.
-
zrangebyscore(name, min, max, start=None, num=None, withscores=False, score_cast_func=<type 'float'>)¶ Return a range of values from the sorted set
namewith scores betweenminandmax.If
startandnumare specified, then return a slice of the range.withscoresindicates to return the scores along with the values. The return type is a list of (value, score) pairsscore_cast_func` a callable used to cast the score return value
-
zrank(name, value)¶ Returns a 0-based value indicating the rank of
valuein sorted setname
-
zrem(name, *values)¶ Remove member
valuesfrom sorted setname
-
zremrangebylex(name, min, max)¶ Remove all elements in the sorted set
namebetween the lexicographical range specified byminandmax.Returns the number of elements removed.
-
zremrangebyrank(name, min, max)¶ Remove all elements in the sorted set
namewith ranks betweenminandmax. Values are 0-based, ordered from smallest score to largest. Values can be negative indicating the highest scores. Returns the number of elements removed
-
zremrangebyscore(name, min, max)¶ Remove all elements in the sorted set
namewith scores betweenminandmax. Returns the number of elements removed.
-
zrevrange(name, start, end, withscores=False, score_cast_func=<type 'float'>)¶ Return a range of values from sorted set
namebetweenstartandendsorted in descending order.startandendcan be negative, indicating the end of the range.withscoresindicates to return the scores along with the values The return type is a list of (value, score) pairsscore_cast_funca callable used to cast the score return value
-
zrevrangebyscore(name, max, min, start=None, num=None, withscores=False, score_cast_func=<type 'float'>)¶ Return a range of values from the sorted set
namewith scores betweenminandmaxin descending order.If
startandnumare specified, then return a slice of the range.withscoresindicates to return the scores along with the values. The return type is a list of (value, score) pairsscore_cast_funca callable used to cast the score return value
-
zrevrank(name, value)¶ Returns a 0-based value indicating the descending rank of
valuein sorted setname
-
zscan(name, cursor=0, match=None, count=None, score_cast_func=<type 'float'>)¶ Incrementally return lists of elements in a sorted set. Also return a cursor indicating the scan position.
matchallows for filtering the keys by patterncountallows for hint the minimum number of returnsscore_cast_funca callable used to cast the score return value
-
zscan_iter(name, match=None, count=None, score_cast_func=<type 'float'>)¶ Make an iterator using the ZSCAN command so that the client doesn’t need to remember the cursor position.
matchallows for filtering the keys by patterncountallows for hint the minimum number of returnsscore_cast_funca callable used to cast the score return value
-
zscore(name, value)¶ Return the score of element
valuein sorted setname
-
zunionstore(dest, keys, aggregate=None)¶ Union multiple sorted sets specified by
keysinto a new sorted set,dest. Scores in the destination will be aggregated based on theaggregate, or SUM if none is provided.
-