HEX
Server: LiteSpeed
System: Linux linux31.centraldnserver.com 4.18.0-553.83.1.lve.el8.x86_64 #1 SMP Wed Nov 12 10:04:12 UTC 2025 x86_64
User: salamatk (1501)
PHP: 8.1.33
Disabled: show_source, system, shell_exec, passthru, exec, popen, proc_open
Upload Files
File: //lib/python3.6/site-packages/redis/__pycache__/client.cpython-36.pyc
3

be�^{o�@s�ddlmZddlmZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZm
Z
mZmZmZmZmZmZmZddlmZmZmZddlmZddlmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$dZ%d	Z&d
d�Z'dd
�Z(dd�Z)dd�Z*Gdd�de+�Z,dd�Z-dd�Z.dd�Z/dd�Z0e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1d�Z2dd�Z3dd �Z4d!d"�Z5d#d$�Z6d%d&�Z7d'd(�Z8dtd*d+�Z9d,d-�Z:d.d/�Z;d0d1�Z<d2d3�Z=d4d5�Z>d6d7�Z?d8d9�Z@d:d;�ZAd<d=�ZBd>d?�ZCd@dA�ZDdBdC�ZEdDdE�ZFdFdG�ZGdHdI�ZHdJdK�ZIdLdM�ZJdNdO�ZKdPdQ�ZLdRdS�ZMdTdU�ZNdVdW�ZOdXdY�ZPdZd[�ZQd\d]�ZRd^d_�ZSd`da�ZTdbdc�ZUddde�ZVGdfdg�dgeW�ZXeXZYGdhdi�dieW�ZZGdjdk�dkeW�Z[Gdldm�dmej\�Z]Gdndo�doeX�Z^Gdpdq�dqeW�Z_Gdrds�dseW�Z`dS)u�)�unicode_literals)�chainN)	�
basestring�imap�	iteritems�iterkeys�
itervalues�izip�long�	nativestr�safe_unicode)�ConnectionPool�UnixDomainSocketConnection�
SSLConnection)�Lock)	�ConnectionError�	DataError�ExecAbortError�
NoScriptError�PubSubError�
RedisError�
ResponseError�TimeoutError�
WatchError��EMPTY_RESPONSEcCsXy*t|�t|ttf�r |g}nt|�}Wntk
rD|g}YnX|rT|j|�|S)N)�iter�
isinstancer�bytes�list�	TypeError�extend)�keys�args�r$�/usr/lib/python3.6/client.py�list_or_argss
r&cCs6|sdSyt|�}Wntk
r(dSXtjj|�S)z5Converts a unix timestamp to a Python datetime objectN)�int�
ValueError�datetimeZ
fromtimestamp)�responser$r$r%�timestamp_to_datetime0sr+cCstj|j�|�S)N)�dict�fromkeys�split)Z
key_string�callbackr$r$r%�string_keys_to_dict;sr0cGs i}x|D]}|j|�q
W|S)N)�update)ZdictsZmerged�dr$r$r%�
dict_merge?s
r3csfeZdZdZdd�Z�fdd�Z�fdd�Z�fdd	�Zd�fdd�	Z�fd
d�Z	�fdd�Z
�ZS)�CaseInsensitiveDictz?Case insensitive dict implementation. Assumes string keys only.cCs&x t|�D]\}}|||j�<q
WdS)N)r�upper)�self�data�k�vr$r$r%�__init__IszCaseInsensitiveDict.__init__cstt|�j|j��S)N)�superr4�__contains__r5)r6r8)�	__class__r$r%r<Msz CaseInsensitiveDict.__contains__cstt|�j|j��dS)N)r;r4�__delitem__r5)r6r8)r=r$r%r>PszCaseInsensitiveDict.__delitem__cstt|�j|j��S)N)r;r4�__getitem__r5)r6r8)r=r$r%r?SszCaseInsensitiveDict.__getitem__Ncstt|�j|j�|�S)N)r;r4�getr5)r6r8�default)r=r$r%r@VszCaseInsensitiveDict.getcstt|�j|j�|�dS)N)r;r4�__setitem__r5)r6r8r9)r=r$r%rBYszCaseInsensitiveDict.__setitem__cst|�}tt|�j|�dS)N)r4r;r1)r6r7)r=r$r%r1\szCaseInsensitiveDict.update)N)�__name__�
__module__�__qualname__�__doc__r:r<r>r?r@rBr1�
__classcell__r$r$)r=r%r4Fsr4cCsTt|�}d|}tdd�|j�D��}d}x$|D]}||kr0t||�||<q0W|S)	zDParse the results of Redis's DEBUG OBJECT command into a Python dictztype:css|]}|jd�VqdS)�:N)r.)�.0Zkvr$r$r%�	<genexpr>gsz%parse_debug_object.<locals>.<genexpr>�refcount�serializedlength�lru�lru_seconds_idle)rKrLrMrN)rr,r.r')r*Z
int_fieldsZfieldr$r$r%�parse_debug_objectas
rOcCs|dkrt|�S|S)z&Parse the results of an OBJECT command�idletimerK)rPrK)�int_or_none)r*�infotyper$r$r%�parse_objectssrScs�i}t|�}�fdd��xv|j�D]j}|r"|jd�r"|jd�dkrz|jdd�\}}|dkrl|jdd�\}}�|�||<q"|jdg�j|�q"W|S)	z;Parse the result of Redis's INFO command into a Python dictcs�d|ksd|krDyd|kr"t|�St|�SWq|tk
r@|SXn8i}x.|jd�D] }|jdd�\}}�|�||<qTW|SdS)N�,�=�.�)�floatr'r(r.�rsplit)�valueZsub_dict�itemr8r9)�	get_valuer$r%r\szparse_info.<locals>.get_value�#rHrWZcmdstat_hostZ__raw__���)r�
splitlines�
startswith�findr.rY�
setdefault�append)r*�info�line�keyrZr$)r\r%�
parse_infozsrgcKsDt|ddd�}x0t|�D]$\}}|jd�rt|ddd�||<qW|S)z!Parse the results of MEMORY STATST)�decode_keys�decode_string_valueszdb.)�
pairs_to_dictrr`)r*�kwargsZstatsrfrZr$r$r%�parse_memory_stats�s
rl)zcan-failover-its-masterzconfig-epochzdown-after-millisecondszfailover-timeoutzinfo-refreshzlast-hello-messagezlast-ok-ping-replyzlast-ping-replyzlast-ping-sentzmaster-link-down-timezmaster-portznum-other-sentinelsz
num-slaveszo-down-timezpending-commandszparallel-syncs�port�quorumzrole-reported-timezs-down-timezslave-priorityzslave-repl-offsetzvoted-leader-epochcCs>t|t�}t|djd��}xdD]\}}||k||<q"W|S)N�flagsrT�	is_master�master�is_slave�slave�is_sdown�s_down�is_odown�o_down�is_sentinel�sentinel�is_disconnected�disconnected�is_master_down�master_down�rprq�rrrs�rtru�rvrw�rxry�rzr{�r|r})r~rr�r�r�r�r�)�pairs_to_dict_typed�SENTINEL_STATE_TYPES�setr.)r[�resultro�name�flagr$r$r%�parse_sentinel_state�s
r�cCsttt|��S)N)r�rr)r*r$r$r%�parse_sentinel_master�sr�cCs0i}x&|D]}ttt|��}|||d<q
W|S)Nr�)r�rr)r*r�r[�stater$r$r%�parse_sentinel_masters�s

r�cCsdd�|D�S)NcSsg|]}ttt|���qSr$)r�rr)rIr[r$r$r%�
<listcomp>�sz7parse_sentinel_slaves_and_sentinels.<locals>.<listcomp>r$)r*r$r$r%�#parse_sentinel_slaves_and_sentinels�sr�cCs|r|dt|d�fpdS)NrrW)r')r*r$r$r%�parse_sentinel_get_master�sr�cCst|t�rt|�S|S)N)rrr)rZr$r$r%�nativestr_if_bytes�sr�FcCst|dkriS|s|rZ|ddd�}|r0tt|�}|ddd�}|rLtt|�}tt||��St|�}tt||��SdS)z-Create a dict given a list of key/value pairsN�rW)rrr�r,r	r)r*rhrir"�values�itr$r$r%rj�s

rjcCs^t|�}i}xLt||�D]>\}}||krNy|||�}Wntk
rLYnX|||<qW|S)N)rr	�	Exception)r*Z	type_infor�r�rfrZr$r$r%r��sr�cKs>|s|jd�r|S|jdt�}t|�}tt|t||���S)zr
    If ``withscores`` is specified in the options, return the response as
    a list of (value, score) pairs
    �
withscores�score_cast_func)r@rXrrr	r)r*�optionsr�r�r$r$r%�zset_score_pairss
r�cs>�s|jd�r�S|d�tt��fdd�t��D���S)z�
    If ``groups`` is specified, return the response as a list of
    n-element tuples with n being the value found in options['groups']
    �groupscsg|]}�|d���qS)Nr$)rI�i)�nr*r$r%r�"sz&sort_return_tuples.<locals>.<listcomp>)r@rr	�range)r*r�r$)r�r*r%�sort_return_tuplessr�cCs|dkrdSt|�S)N)r')r*r$r$r%rQ%srQcCs|dkrdSt|�S)N)r)r*r$r$r%�nativestr_or_none+sr�cCsP|dkrdSg}x:|D]2}|dk	r>|j|dt|d�f�q|jd�qW|S)NrrW)NN)rcrj)r*r7�rr$r$r%�parse_stream_list1s
r�cCst|dd�S)NT)rh)rj)r*r$r$r%�!pairs_to_dict_with_nativestr_keys=sr�cCsttt|��S)N)rrr�)r*r$r$r%�parse_list_of_dictsAsr�cKs|jdd�r|St|�S)N�parse_justidF)r@r�)r*r�r$r$r%�parse_xclaimEsr�cCs`t|dd�}|d}|dk	r4|dt|d�f|d<|d}|dk	r\|dt|d�f|d<|S)NT)rhzfirst-entryrrWz
last-entry)rj)r*r7�firstZlastr$r$r%�parse_xinfo_streamKsr�cCs|dkrgSdd�|D�S)NcSs g|]}|dt|d�g�qS)rrW)r�)rIr�r$r$r%r�Yszparse_xread.<locals>.<listcomp>r$)r*r$r$r%�parse_xreadVsr�cKsD|jdd�rt|�Sdd�|dp$gD�}|d|d|d|d	�S)
N�parse_detailFcSsg|]\}}|t|�d��qS))r��pending)r
)rIr��pr$r$r%r�_sz"parse_xpending.<locals>.<listcomp>�rrWr�)r��min�max�	consumers)r@�parse_xpending_range)r*r�r�r$r$r%�parse_xpending\sr�csd��fdd�|D�S)N�
message_id�consumer�time_since_delivered�times_deliveredcsg|]}tt�|���qSr$)r,r	)rIr�)r8r$r%r�jsz(parse_xpending_range.<locals>.<listcomp>)r�r�r�r�r$)r*r$)r8r%r�hsr�cCs|dkrdSt|�S)N)rX)r*r$r$r%�
float_or_nonemsr�cCst|�dkS)N�OK)r)r*r$r$r%�bool_okssr�cKs&|dkrdS|jd�rt|�St|�S)N�as_score)r@rXr')r*r�r$r$r%�
parse_zaddws

r�cKs<g}x2t|�j�D]"}|jtdd�|jd�D���qW|S)Ncss|]}|jdd�VqdS)rUrWN)r.)rI�pairr$r$r%rJ�sz$parse_client_list.<locals>.<genexpr>� )rr_rcr,r.)r*r�Zclients�cr$r$r%�parse_client_lists"r�cKsdd�|D�}|rt|�piS)NcSs g|]}|dk	rt|�nd�qS)N)r)rIr�r$r$r%r��sz$parse_config_get.<locals>.<listcomp>)rj)r*r�r$r$r%�parse_config_get�sr�cKs|\}}t|�|fS)N)r
)r*r��cursorr�r$r$r%�
parse_scan�sr�cKs |\}}t|�|rt|�pifS)N)r
rj)r*r�r�r�r$r$r%�parse_hscan�sr�cKs8|jdt�}|\}}t|�}t|�tt|t||���fS)Nr�)r@rXrr
rr	r)r*r�r�r�r�r�r$r$r%�parse_zscan�sr�cs&|jdd�rdnd��fdd�|D�S)N�decode_responsesFr�� cs8g|]0}|dt|d�t|d��j|d�d��qS)rrWr�r�)�idZ
start_timeZduration�command)r'�join)rIr[)�spacer$r%r��sz%parse_slowlog_get.<locals>.<listcomp>)r@)r*r�r$)r�r%�parse_slowlog_get�s
r�cKst|�}tdd�|j�D��S)Ncss|]}|r|jd�VqdS)rHN)r.)rIrer$r$r%rJ�sz%parse_cluster_info.<locals>.<genexpr>)rr,r_)r*r�r$r$r%�parse_cluster_info�sr�c	Csl|jd�}|jd�dd�\}}}}}}}}	dd�|dd�D�}
|||||||
|	dkr\dndd�}||fS)	Nr��cSsg|]}|jd��qS)�-)r.)rIZslr$r$r%r��sz$_parse_node_line.<locals>.<listcomp>�	connectedTF)�node_idro�	master_idZlast_ping_sentZlast_pong_rcvd�epoch�slotsr�)r.)reZ
line_itemsr��addrror��ping�pongr�r�r�Z	node_dictr$r$r%�_parse_node_line�s
"r�cKs0t|�}|}t|t�r|j�}tdd�|D��S)Ncss|]}t|�VqdS)N)r�)rIrer$r$r%rJ�sz&parse_cluster_nodes.<locals>.<genexpr>)rrrr_r,)r*r�Z	raw_linesr$r$r%�parse_cluster_nodes�s

r�cs��ds�dr|St|�tkr(|g}n|}�drN�drN�drN|Stdd�td��d	d�g����fd
d�d
D�7��fdd�|D�S)N�store�
store_dist�withdist�	withcoord�withhashcSst|d�t|d�fS)NrrW)rX)�llr$r$r%�<lambda>�sz)parse_georadius_generic.<locals>.<lambda>)r�r�r�cSs|S)Nr$)�xr$r$r%r��scsg|]}�|r�|�qSr$r$)rI�o)�castr�r$r%r��sz+parse_georadius_generic.<locals>.<listcomp>cs$g|]}ttdd�t�|����qS)cSs|d|d�S)NrrWr$)Zfvr$r$r%r��sz4parse_georadius_generic.<locals>.<listcomp>.<lambda>)r�map�zip)rIr�)�fr$r%r��s)r�r�r�)�typerrXr')r*r�Z
response_listr$)r�r�r�r%�parse_georadius_generic�s

r�cKs"tt|ddd�|ddd���S)Nrr�rW)rr�)r*r�r$r$r%�parse_pubsub_numsub�sr�cKs"t|ttf�rt|�St|�dkS)Nr�)rr
r'r)r*r�r$r$r%�parse_client_kill�sr�cKs�|dkrdSt|dd�}ttt|d��|d<ttt|d��|d<t|d�|d<gg}}x4|djd�D]"}d|kr�|j|�qn|j|�qnW||d<||d<d	|dk|d
<|S)NT)rhro�	passwords�commandsr��@�
categoriesZon�enabled)rjrr�rr.rc)r*r�r7r�r�r�r$r$r%�parse_acl_getuser�s
r�cc@s�eZdZdZeede�ede�ede�eddd��ede	�ed	e
�ed
e�eddd��ed
dd��ede�eddd��ede
�ede�ede�eddd��dd�eeedd�eeedd�edd�eeeedd�eedd�dd�eeeedd�eeeeeeeeeeeedd�d d�eed!d�eeeeee
ed"d�ed#d�ed$d�eeee e!e"eee#ee#d%d�e$eeed&d�e%eeeee&e&e'e(e)e*d'�R�Z+e,�dd)d*��Z-�dd2d3�Z.d4d5�Z/d6d7�Z0�dd9d:�Z1d;d<�Z2�dd>d?�Z3d@dA�Z4dBdC�Z5dDdE�Z6dFdG�Z7dHdI�Z8dJdK�Z9dLdM�Z:dNdO�Z;dPdQ�Z<�d dRdS�Z=dTdU�Z>dVdW�Z?dXdY�Z@dZd[�ZAd\d]�ZBd^d_�ZC�d!d`da�ZDdbdc�ZEddde�ZFdfdg�ZGdhdi�ZHdjdk�ZI�d"dldm�ZJ�d#dndo�ZKdpdq�ZLdrds�ZMdtdu�ZN�d$dvdw�ZOdxdy�ZPdzd{�ZQd|d}�ZR�d%dd��ZSd�d��ZTd�d��ZUd�d��ZVd�d��ZWd�d��ZXd�d��ZY�d&d�d��ZZ�d'd�d��Z[d�d��Z\�d(d�d��Z]d�d��Z^�d)d�d��Z_d�d��Z`d�d��Za�d*d�d��Zbd�d��Zcd�d��Zdd�d��Zed�d��Zfd�d��Zgd�d��Zhd�d��Zid�d��Zjd�d��Zkd�d��Zld�d��Zmd�d��Zn�d+d�d��Zo�d,d�d��Zp�d-d�d��Zqd�d��Zrd�d��Zsd�d„Ztd�dĄZud�dƄZv�d.d�dȄZw�d/d�dʄZxd�d̄Zy�d0d�d΄Zz�d1d�dфZ{�d2d�dӄZ|d�dՄZ}d�dׄZ~d�dلZd�dۄZ�e�Z�d�d݄Z�d�d߄Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z�d�d�Z��d3d�d�Z��d4d�d�Z��d5d�d�Z��d6d�d�Z�d�d�Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d��d�Z��d�d�Z��d�d�Z��d�d�Z��d�d�Z��d	�d
�Z��d7�d�d�Z��d8�d
�d�Z��d�d�Z��d�d�Z��d�d�Z��d�d�Z��d�d�Z��d�d�Z��d:�d�d�Z��d�d�Z��d�d �Z��d!�d"�Z��d#�d$�Z��d%�d&�Z��d'�d(�Z��d;�d)�d*�Z��d<�d+�d,�Z��d=�d-�d.�Z��d/�d0�Z��d1�d2�Z��d3�d4�Z��d5�d6�Z��d7�d8�Z��d9�d:�Z��d;�d<�Z��d=�d>�Z��d?�d@�Z��dA�dB�Z��dC�dD�Z��dE�dF�Z��dG�dH�Z��dI�dJ�Z��d>�dK�dL�Z��d?�dM�dN�Z��d@�dO�dP�Z��dA�dQ�dR�Z��dB�dS�dT�Z��dC�dU�dV�Z��dD�dW�dX�Z�d-d(d(ef�dY�dZ�Z�d(d(ef�d[�d\�Z��d]�d^�Zd_�d`�ZÐda�db�ZĐdc�dd�ZŐde�df�ZƐdg�dh�Zǐdi�dj�ZȐdk�dl�Zɐdm�dn�ZʐdE�do�dp�ZːdF�dq�dr�Z̐ds�dt�Z͐du�dv�Zΐdw�dx�Zϐdy�dz�ZАdG�d{�d|�ZѐdH�d}�d~�ZҐd�d��ZӐdI�d��d��ZԐd��d��ZՐd��d��Z֐d��d��Zאd��d��Zؐd��d��Zِd��d��Zڐd��d��Zېd��d��ZܐdJ�d��d��ZݐdK�d��d��ZސdL�d��d��ZߐdM�d��d��Z�dN�d��d��Z�dO�d��d��Z�dP�d��d��Z�d��d��Z�d��d��Z�d��d��Z�dQ�d��d��Z�d��d��Z�dR�d��d��Z�dS�d��d��Z�dT�d��d��Z�dU�d��d��Z�d0d0ef�d��d��Z�dV�d��d��Z�dW�d��d��Z�d(d(d0ef�d��d��Z�d��d��Z�d��d��Z�ddÄZ�dĐdńZ�dƐdDŽZ�d0ef�dȐdɄZ�d(d(d0ef�dʐd˄Z��d̐d̈́Z��dΐdτZ��dX�dАdфZ��dY�dҐdӄZ��dԐdՄZ��d֐dׄZ��dؐdلZ��dڐdۄZ��dܐd݄�Z�dސd߄�Z�d�d��Z�dZ�d�d��Z�d[�d�d��Z�d�d��Z�d�d��Z�d\�d�d��Z�d�d��Z�d�d��Z	�d�d��Z
�d�d��Z�d�d���Z�d��d���Z
�d]�d��d���Z�d��d���Z�d��d���Z�d��d���Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d	��Z�d
�d��Z�d�d
��Z�d�d��Z�d^�d�d��Z�d�d��Z�d�d��Z�d_�d�d��Z�d`�d�d��Z�d�d��Zd(S(a�Redisa&
    Implementation of the Redis protocol.

    This abstract class provides a Python interface to all Redis commands
    and an implementation of the Redis protocol.

    Connection and Pipeline derive from this, implementing how
    the commands are sent and received to the Redis server
    zbAUTH EXPIRE EXPIREAT HEXISTS HMSET MOVE MSETNX PERSIST PSETEX RENAMENX SISMEMBER SMOVE SETEX SETNXaBITCOUNT BITPOS DECRBY DEL EXISTS GEOADD GETBIT HDEL HLEN HSTRLEN INCRBY LINSERT LLEN LPUSHX PFADD PFCOUNT RPUSHX SADD SCARD SDIFFSTORE SETBIT SETRANGE SINTERSTORE SREM STRLEN SUNIONSTORE UNLINK XACK XDEL XLEN XTRIM ZCARD ZLEXCOUNT ZREM ZREMRANGEBYLEX ZREMRANGEBYRANK ZREMRANGEBYSCOREzINCRBYFLOAT HINCRBYFLOATzLPUSH RPUSHcCst|ttf�r|pt|�dkS)Nr�)rr
r'r)r�r$r$r%r�&szRedis.<lambda>�SORTzZSCORE ZINCRBY GEODISTzuFLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE READONLY READWRITE RENAME SAVE SELECT SHUTDOWN SLAVEOF SWAPDB WATCH UNWATCH zBLPOP BRPOPcCs|rt|�pdS)N)�tuple)r�r$r$r%r�/szSDIFF SINTER SMEMBERS SUNIONcCs|rt|�pt�S)N)r�)r�r$r$r%r�2sz?ZPOPMAX ZPOPMIN ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCOREzBZPOPMIN BZPOPMAXcCs"|r|d|dt|d�fp dS)NrrWr�)rX)r�r$r$r%r�9szZRANK ZREVRANKzXREVRANGE XRANGEzXREAD XREADGROUPzBGREWRITEAOF BGSAVEcCsdS)NTr$)r�r$r$r%r�=scCsttt|��S)N)rr�r)r�r$r$r%r�?scCsttt|��S)N)rr�r)r�r$r$r%r�CscCsttt|��S)N)rr�r)r�r$r$r%r�GscCs|o
t|�S)N)r)r�r$r$r%r�IscCs|rt|�dkpdS)NrWF)r')r�r$r$r%r�NscCst|�S)N)r')r�r$r$r%r�QscCst|�S)N)r')r�r$r$r%r�RscCst|�S)N)r')r�r$r$r%r�WscCsttt|��S)N)rr�r�)r�r$r$r%r�dscCsttdd�|��S)NcSs$|dk	r t|d�t|d�fSdS)NrrW)rX)r�r$r$r%r�esz Redis.<lambda>.<locals>.<lambda>)rr�)r�r$r$r%r�es
cCs|rt|�piS)N)rj)r�r$r$r%r�jscCst|�dkS)NZPONG)r)r�r$r$r%r�rscCs|r|p
dS)Nr$)r�r$r$r%r�tscCsttt|��S)N)rr�bool)r�r$r$r%r�vscCs|ot|�dkS)Nr�)r)r�r$r$r%r��scCst|d�t|d�fS)NrrW)r')r�r$r$r%r��s)RzACL CATzACL DELUSERzACL GENPASSzACL GETUSERzACL LISTzACL LOADzACL SAVEzACL SETUSERz	ACL USERSz
ACL WHOAMIzCLIENT GETNAMEz	CLIENT IDzCLIENT KILLzCLIENT LISTzCLIENT SETNAMEzCLIENT UNBLOCKzCLIENT PAUSEzCLUSTER ADDSLOTSzCLUSTER COUNT-FAILURE-REPORTSzCLUSTER COUNTKEYSINSLOTzCLUSTER DELSLOTSzCLUSTER FAILOVERzCLUSTER FORGETzCLUSTER INFOzCLUSTER KEYSLOTzCLUSTER MEETz
CLUSTER NODESzCLUSTER REPLICATEz
CLUSTER RESETzCLUSTER SAVECONFIGzCLUSTER SET-CONFIG-EPOCHzCLUSTER SETSLOTzCLUSTER SLAVESz
CONFIG GETzCONFIG RESETSTATz
CONFIG SETzDEBUG OBJECT�GEOHASH�GEOPOS�	GEORADIUS�GEORADIUSBYMEMBER�HGETALL�HSCAN�INFO�LASTSAVEzMEMORY PURGEzMEMORY STATSzMEMORY USAGE�OBJECT�PINGz
PUBSUB NUMSUB�	RANDOMKEY�SCANz
SCRIPT EXISTSzSCRIPT FLUSHzSCRIPT KILLzSCRIPT LOADz SENTINEL GET-MASTER-ADDR-BY-NAMEzSENTINEL MASTERzSENTINEL MASTERSzSENTINEL MONITORzSENTINEL REMOVEzSENTINEL SENTINELSzSENTINEL SETzSENTINEL SLAVES�SETzSLOWLOG GETzSLOWLOG LENz
SLOWLOG RESET�SSCAN�TIME�XCLAIMz
XGROUP CREATEzXGROUP DELCONSUMERzXGROUP DESTROYzXGROUP SETIDzXINFO CONSUMERSzXINFO GROUPSzXINFO STREAM�XPENDING�ZADD�ZSCANNcKs tj|fd|i|��}||d�S)a<
        Return a Redis client object configured from the given URL

        For example::

            redis://[[username]:[password]]@localhost:6379/0
            rediss://[[username]:[password]]@localhost:6379/0
            unix://[[username]:[password]]@/path/to/socket.sock?db=0

        Three URL schemes are supported:

        - ```redis://``
          <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ creates a
          normal TCP socket connection
        - ```rediss://``
          <http://www.iana.org/assignments/uri-schemes/prov/rediss>`_ creates a
          SSL wrapped TCP socket connection
        - ``unix://`` creates a Unix Domain Socket connection

        There are several ways to specify a database number. The parse function
        will return the first specified option:
            1. A ``db`` querystring option, e.g. redis://localhost?db=0
            2. If using the redis:// scheme, the path argument of the url, e.g.
               redis://localhost/0
            3. The ``db`` argument to this function.

        If none of these options are specified, db=0 is used.

        Any additional querystring arguments and keyword arguments will be
        passed along to the ConnectionPool class's initializer. In the case
        of conflicting arguments, querystring arguments always win.
        �db)�connection_pool)r
�from_url)�clsZurlrrkrr$r$r%r	�s"zRedis.from_url�	localhost��r�utf-8�strictF�requiredcCs�|	s�|
dk	rtjtd��|
}|dk	r8tjtd��|}|||||||||||d�}|
dk	rn|j|
td��n2|j|||||d��|r�|jt|||||d��tf|�}	|	|_d|_|r�|jj	d�|_t
|jj�|_
dS)Nz/"charset" is deprecated. Use "encoding" insteadz5"errors" is deprecated. Use "encoding_errors" instead)r�username�password�socket_timeout�encoding�encoding_errorsr��retry_on_timeout�max_connections�health_check_interval�client_name)�path�connection_class)�hostrm�socket_connect_timeout�socket_keepalive�socket_keepalive_options)r�ssl_keyfile�ssl_certfile�
ssl_cert_reqs�ssl_ca_certs�ssl_check_hostname�_)�warnings�warn�DeprecationWarningr1rrr
r�
connection�get_connectionr4r=�RESPONSE_CALLBACKS�response_callbacks)r6rrmrrrrrrrZunix_socket_pathrr�charset�errorsr�rZsslrr r!r"r#r�single_connection_clientrrrrkr$r$r%r:�sZ



zRedis.__init__cCsdt|�jt|j�fS)Nz%s<%s>)r�rC�reprr)r6r$r$r%�__repr__szRedis.__repr__cCs||j|<dS)zSet a custom Response CallbackN)r+)r6r�r/r$r$r%�set_response_callbackszRedis.set_response_callbackTcCst|j|j||�S)a_
        Return a new pipeline object that can queue multiple commands for
        later execution. ``transaction`` indicates whether all commands
        should be executed atomically. Apart from making a group of operations
        atomic, pipelines are useful for reducing the back-and-forth overhead
        between the client and server.
        )�Pipelinerr+)r6�transaction�
shard_hintr$r$r%�pipelines
zRedis.pipelinec
Os�|jdd�}|jdd�}|jdd�}|jd|��h}x`y*|rD|j|�||�}|j�}	|r\|S|	Stk
r�|dk	r�|dkr�tj|�w4Yq4Xq4WWdQRXdS)z�
        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.
        r4N�value_from_callableF�watch_delayTr)�popr5�watch�executer�time�sleep)
r6�funcZwatchesrkr4r6r7�pipeZ
func_valueZ
exec_valuer$r$r%r3s

zRedis.transaction皙�����?cCs |dkrt}|||||||d�S)a$	
        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
        when the lock is in blocking mode and another client is currently
        holding the lock.

        ``blocking_timeout`` indicates the maximum amount of time in seconds to
        spend trying to acquire the lock. A value of ``None`` indicates
        continue trying forever. ``blocking_timeout`` can be specified as a
        float or integer, both representing the number of seconds to wait.

        ``lock_class`` forces the specified lock implementation.

        ``thread_local`` indicates 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.        N)�timeoutr<�blocking_timeout�thread_local)r)r6r�r@r<rAZ
lock_classrBr$r$r%�lock,s
-
z
Redis.lockcKst|jf|�S)z�
        Return a Publish/Subscribe object. With this object, you can
        subscribe to channels and listen for messages that get published to
        them.
        )�PubSubr)r6rkr$r$r%�pubsub_szRedis.pubsubcCs
t|j�S)N)�Monitorr)r6r$r$r%�monitorgsz
Redis.monitorcCs|j|jdd�S)NT)rr.)r=r)r6r$r$r%�clientjszRedis.clientcCs|S)Nr$)r6r$r$r%�	__enter__nszRedis.__enter__cCs|j�dS)N)�close)r6�exc_type�	exc_value�	tracebackr$r$r%�__exit__qszRedis.__exit__cCs|j�dS)N)rJ)r6r$r$r%�__del__tsz
Redis.__del__cCs |j}|rd|_|jj|�dS)N)r(r�release)r6�connr$r$r%rJwszRedis.closecOs�|j}|d}|jp |j|f|�}zty|j|�|j||f|�Sttfk
r�}z4|j�|jojt	|t�sn�|j|�|j||f|�Sd}~XnXWd|js�|j
|�XdS)z.Execute a command and return a parsed responserN)rr(r)�send_command�parse_responserr�
disconnectrrrP)r6r#r�Zpool�command_namerQ�er$r$r%�execute_command~s

 zRedis.execute_commandcKsTy|j�}Wn&tk
r2t|kr,|tS�YnX||jkrP|j||f|�S|S)z'Parses a response from the Redis server)�
read_responserrr+)r6r(rUr�r*r$r$r%rS�s
zRedis.parse_responsecCs|r
|gng}|jd|��S)z�
        Returns a list of categories or commands within a category.

        If ``category`` is not supplied, returns a list of all categories.
        If ``category`` is supplied, returns a list of all commands within
        that category.
        �ACL CAT)rY)rW)r6�category�piecesr$r$r%�acl_cat�sz
Redis.acl_catcCs|jd|�S)z-Delete the ACL for the specified ``username``zACL DELUSER)rW)r6rr$r$r%�acl_deluser�szRedis.acl_delusercCs
|jd�S)z Generate a random password valuezACL GENPASS)rW)r6r$r$r%�acl_genpass�szRedis.acl_genpasscCs|jd|�S)zz
        Get the ACL details for the specified ``username``.

        If ``username`` does not exist, return None
        zACL GETUSER)rW)r6rr$r$r%�acl_getuser�szRedis.acl_getusercCs
|jd�S)z'Return a list of all ACLs on the serverzACL LIST)rW)r6r$r$r%�acl_list�szRedis.acl_listcCs
|jd�S)z�
        Load ACL rules from the configured ``aclfile``.

        Note that the server must be configured with the ``aclfile``
        directive to be able to load ACL rules from an aclfile.
        zACL LOAD)rW)r6r$r$r%�acl_load�szRedis.acl_loadcCs
|jd�S)z�
        Save ACL rules to the configured ``aclfile``.

        Note that the server must be configured with the ``aclfile``
        directive to be able to save ACL rules to an aclfile.
        zACL SAVE)rW)r6r$r$r%�acl_save�szRedis.acl_savecCs�|jj�}|g}
|	r|
jd�|
r,|
jd�|r:|
jd�|rJ|
jd�n
|
jd�|s\|rh|rhtd��|r�t|g�}xnt|�D]b\}}|j|�}|jd�r�|
jd|d	d
��q�|jd�r�|
jd|d	d
��q�td
|��q�W|�rlt|g�}xtt|�D]h\}}|j|�}|jd��r6|
jd|d	d
��n0|jd��rZ|
jd|d	d
��ntd|���qW|�r||
jd�|�r*x�|D]�}|j|�}|jd��r�|
j|�nv|jd��r�|
jd|d	d
��nR|jd��r�|
j|�n:|jd��r|
jd|d	d
��ntd|j|dd����q�W|�r�xT|D]L}|j|�}|jd��rv|jd��rvtd|j|dd���|
j|��q6W|�r�x&|D]}|j|�}|
jd|��q�W|j	d|
��S)aE
        Create or update an ACL user.

        Create or update the ACL for ``username``. If the user already exists,
        the existing ACL is completely overwritten and replaced with the
        specified values.

        ``enabled`` is a boolean indicating whether the user should be allowed
        to authenticate or not. Defaults to ``False``.

        ``nopass`` is a boolean indicating whether the can authenticate without
        a password. This cannot be True if ``passwords`` are also specified.

        ``passwords`` if specified is a list of plain text passwords
        to add to or remove from the user. Each password must be prefixed with
        a '+' to add or a '-' to remove. For convenience, the value of
        ``add_passwords`` can be a simple prefixed string when adding or
        removing a single password.

        ``hashed_passwords`` if specified is a list of SHA-256 hashed passwords
        to add to or remove from the user. Each hashed password must be
        prefixed with a '+' to add or a '-' to remove. For convenience,
        the value of ``hashed_passwords`` can be a simple prefixed string when
        adding or removing a single password.

        ``categories`` if specified is a list of strings representing category
        permissions. Each string must be prefixed with either a '+' to add the
        category permission or a '-' to remove the category permission.

        ``commands`` if specified is a list of strings representing command
        permissions. Each string must be prefixed with either a '+' to add the
        command permission or a '-' to remove the command permission.

        ``keys`` if specified is a list of key patterns to grant the user
        access to. Keys patterns allow '*' to support wildcard matching. For
        example, '*' grants access to all keys while 'cache:*' grants access
        to all keys that are prefixed with 'cache:'. ``keys`` should not be
        prefixed with a '~'.

        ``reset`` is a boolean indicating whether the user should be fully
        reset prior to applying the new ACL. Setting this to True will
        remove all existing passwords, flags and privileges from the user and
        then apply the specified rules. If this is False, the user's existing
        passwords, flags and privileges will be kept and any new specified
        rules will be applied on top.

        ``reset_keys`` is a boolean indicating whether the user's key
        permissions should be reset prior to applying any new key permissions
        specified in ``keys``. If this is False, the user's existing
        key permissions will be kept and any new specified key permissions
        will be applied on top.

        ``reset_passwords`` is a boolean indicating whether to remove all
        existing passwords and the 'nopass' flag from the user prior to
        applying any new passwords specified in 'passwords' or
        'hashed_passwords'. If this is False, the user's existing passwords
        and 'nopass' status will be kept and any new specified passwords
        or hashed_passwords will be applied on top.
        sresets	resetkeyss	resetpasssonsoffz@Cannot set 'nopass' and supply 'passwords' or 'hashed_passwords'�+s>%srWN�-s<%szBPassword %d must be prefixeed with a "+" to add or a "-" to removes#%ss!%szIHashed %d password must be prefixeed with a "+" to add or a "-" to removesnopasss+@s+@%ss-@s-@%sz.Category "%s" must be prefixed with "+" or "-"T)�forcez-Command "%s" must be prefixed with "+" or "-"s~%s�ACL SETUSER)rf)
r�get_encoderrcrr&�	enumerate�encoder`�decoderW)r6rr�Znopassr�Zhashed_passwordsr�r�r"�resetZ
reset_keysZreset_passwords�encoderr[r�rZhashed_passwordrZ�cmdrfr$r$r%�acl_setuser�sx?

















zRedis.acl_setusercCs
|jd�S)z5Returns a list of all registered users on the server.z	ACL USERS)rW)r6r$r$r%�	acl_userscszRedis.acl_userscCs
|jd�S)z+Get the username for the current connectionz
ACL WHOAMI)rW)r6r$r$r%�
acl_whoamigszRedis.acl_whoamicCs
|jd�S)zBTell the Redis server to rewrite the AOF file from data in memory.ZBGREWRITEAOF)rW)r6r$r$r%�bgrewriteaofkszRedis.bgrewriteaofcCs
|jd�S)z�
        Tell the Redis server to save its data to disk.  Unlike save(),
        this method is asynchronous and returns immediately.
        ZBGSAVE)rW)r6r$r$r%�bgsaveoszRedis.bgsavecCs|jd|�S)z/Disconnects the client at ``address`` (ip:port)zCLIENT KILL)rW)r6Zaddressr$r$r%�client_killvszRedis.client_killcCs�g}|dk	r<d}t|�j�|kr.td|f��|jd|f�|dk	rpt|t�sVtd��|rf|jd�n
|jd�|dk	r�|jd|f�|dk	r�|jd
|f�|s�td��|jd|��S)a

        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 the client calling the command
        will not get killed even if it is identified by one of the filter
        options. If skipme is not provided, the server defaults to skipme=True
        N�normalrqrsrEz"CLIENT KILL type must be one of %rsTYPEz!CLIENT KILL skipme must be a bool�SKIPME�YES�NOsIDsADDRzVCLIENT KILL <filter> <value> ... ... <filter> <value> must specify at least one filter�CLIENT KILL)rtrqrsrE)rurv)rurw)rx)�str�lowerrr!rr�rW)r6Z_id�_typer�Zskipmer#�client_typesr$r$r%�client_kill_filterzs(


zRedis.client_kill_filtercCsB|dk	r8d	}t|�j�|kr*td|f��|jdd|�S|jd�S)
z�
        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)
        Nrtrq�replicarEz#CLIENT LIST _type must be one of %rzCLIENT LISTsTYPE)rtrqr~rE)ryrzrrW)r6r{r|r$r$r%�client_list�s
zRedis.client_listcCs
|jd�S)z#Returns the current connection namezCLIENT GETNAME)rW)r6r$r$r%�client_getname�szRedis.client_getnamecCs
|jd�S)z!Returns the current connection idz	CLIENT ID)rW)r6r$r$r%�	client_id�szRedis.client_idcCs|jd|�S)z Sets the current connection namezCLIENT SETNAME)rW)r6r�r$r$r%�client_setname�szRedis.client_setnamecCs$dt|�g}|r|jd�|j|�S)z�
        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.
        zCLIENT UNBLOCKsERROR)r'rcrW)r6r��errorr#r$r$r%�client_unblock�s
zRedis.client_unblockcCs&t|ttf�std��|jdt|��S)z�
        Suspend all the Redis clients for the specified amount of time
        :param timeout: milliseconds to pause clients
        z'CLIENT PAUSE timeout must be an integerzCLIENT PAUSE)rr'r
rrWry)r6r@r$r$r%�client_pause�szRedis.client_pausecCs
|jd�S)zDDisables read queries for a connection to a Redis Cluster slave nodeZ	READWRITE)rW)r6r$r$r%�	readwrite�szRedis.readwritecCs
|jd�S)zEEnables read queries for a connection to a Redis Cluster replica nodeZREADONLY)rW)r6r$r$r%�readonly�szRedis.readonly�*cCs|jd|�S)z=Return a dictionary of configuration based on the ``pattern``z
CONFIG GET)rW)r6�patternr$r$r%�
config_get�szRedis.config_getcCs|jd||�S)z'Set config item ``name`` with ``value``z
CONFIG SET)rW)r6r�rZr$r$r%�
config_set�szRedis.config_setcCs
|jd�S)zReset runtime statisticszCONFIG RESETSTAT)rW)r6r$r$r%�config_resetstat�szRedis.config_resetstatcCs
|jd�S)zERewrite config file with the minimal change to reflect running configzCONFIG REWRITE)rW)r6r$r$r%�config_rewrite�szRedis.config_rewritecCs
|jd�S)z2Returns the number of keys in the current databaseZDBSIZE)rW)r6r$r$r%�dbsize�szRedis.dbsizecCs|jd|�S)z;Returns version specific meta information about a given keyzDEBUG OBJECT)rW)r6rfr$r$r%�debug_object�szRedis.debug_objectcCs|jd|�S)z$Echo the string back from the serverZECHO)rW)r6rZr$r$r%�echo�sz
Redis.echocCs g}|r|jd�|jd|��S)z�
        Delete all keys in all databases on the current host.

        ``asynchronous`` indicates whether the operation is
        executed asynchronously by the server.
        sASYNC�FLUSHALL)r�)rcrW)r6�asynchronousr#r$r$r%�flushall�s
zRedis.flushallcCs g}|r|jd�|jd|��S)z�
        Delete all keys in the current database.

        ``asynchronous`` indicates whether the operation is
        executed asynchronously by the server.
        sASYNC�FLUSHDB)r�)rcrW)r6r�r#r$r$r%�flushdb�s
z
Redis.flushdbcCs|jd||�S)zSwap two databasesZSWAPDB)rW)r6r��secondr$r$r%�swapdb	szRedis.swapdbcCs"|dkr|jd�S|jd|�SdS)a,
        Returns a dictionary containing information about the Redis server

        The ``section`` option can be used to select a specific section
        of information

        The section option is not supported by older versions of Redis Server,
        and will generate ResponseError
        Nr�)rW)r6Zsectionr$r$r%rd
s

z
Redis.infocCs
|jd�S)zy
        Return a Python datetime object representing the last time the
        Redis database was saved to disk
        r�)rW)r6r$r$r%�lastsaveszRedis.lastsavec	
Cs|t|g�}|std��g}	|r(|	jd�|r6|	jd�|rN|	jd�|	j|�|	jd�|	j|�|jd||d||f|	��S)a�
        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 interrupted.

        If ``copy`` is True, the specified ``keys`` are NOT deleted from
        the source server.

        If ``replace`` is True, this operation will overwrite the keys
        on the destination server if they exist.

        If ``auth`` is specified, authenticate to the destination server with
        the password provided.
        z!MIGRATE requires at least one keysCOPYsREPLACEsAUTHsKEYSZMIGRATE�)r&rrcr!rW)
r6rrmr"Zdestination_dbr@�copy�replaceZauthr[r$r$r%�migrate#s






z
Redis.migratecCs|jd|||d�S)z8Return the encoding, idletime, or refcount about the keyr�)rR)rW)r6rRrfr$r$r%�objectFszRedis.objectcCs
|jd�S)z#Return a dictionary of memory statszMEMORY STATS)rW)r6r$r$r%�memory_statsJszRedis.memory_statscCs.g}t|t�r|jd|g�|jd|f|��S)a'
        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.
        sSAMPLESzMEMORY USAGE)rr'r!rW)r6rfZsamplesr#r$r$r%�memory_usageNs	
zRedis.memory_usagecCs
|jd�S)z:Attempts to purge dirty pages for reclamation by allocatorzMEMORY PURGE)rW)r6r$r$r%�memory_purge\szRedis.memory_purgecCs
|jd�S)zPing the Redis serverr�)rW)r6r$r$r%r�`sz
Redis.pingcCs
|jd�S)zm
        Tell the Redis server to save its data to disk,
        blocking until the save is complete
        �SAVE)rW)r6r$r$r%�savedsz
Redis.savecGstjtd��dS)z"Redis Sentinel's SENTINEL command.z%Use the individual sentinel_* methodsN)r%r&r')r6r#r$r$r%rykszRedis.sentinelcCs|jd|�S)z:Returns a (host, port) pair for the given ``service_name``z SENTINEL GET-MASTER-ADDR-BY-NAME)rW)r6�service_namer$r$r%� sentinel_get_master_addr_by_namepsz&Redis.sentinel_get_master_addr_by_namecCs|jd|�S)z<Returns a dictionary containing the specified masters state.zSENTINEL MASTER)rW)r6r�r$r$r%�sentinel_masteruszRedis.sentinel_mastercCs
|jd�S)z>Returns a list of dictionaries containing each master's state.zSENTINEL MASTERS)rW)r6r$r$r%�sentinel_mastersyszRedis.sentinel_masterscCs|jd||||�S)z,Add a new master to Sentinel to be monitoredzSENTINEL MONITOR)rW)r6r�Ziprmrnr$r$r%�sentinel_monitor}szRedis.sentinel_monitorcCs|jd|�S)z*Remove a master from Sentinel's monitoringzSENTINEL REMOVE)rW)r6r�r$r$r%�sentinel_remove�szRedis.sentinel_removecCs|jd|�S)z0Returns a list of sentinels for ``service_name``zSENTINEL SENTINELS)rW)r6r�r$r$r%�sentinel_sentinels�szRedis.sentinel_sentinelscCs|jd|||�S)z5Set Sentinel monitoring parameters for a given masterzSENTINEL SET)rW)r6r�ZoptionrZr$r$r%�sentinel_set�szRedis.sentinel_setcCs|jd|�S)z-Returns a list of slaves for ``service_name``zSENTINEL SLAVES)rW)r6r�r$r$r%�sentinel_slaves�szRedis.sentinel_slavescCsb|r|rtd��dg}|r$|jd�|r2|jd�y|j|�Wntk
rTdSXtd��dS)anShutdown 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.
        z+SHUTDOWN save and nosave cannot both be setZSHUTDOWNr�ZNOSAVENzSHUTDOWN seems to have failed.)rrcrWrr)r6r�Znosaver#r$r$r%�shutdown�s

zRedis.shutdowncCs,|dkr|dkr|jddd�S|jd||�S)z�
        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.
        NZSLAVEOFsNOsONE)rW)r6rrmr$r$r%�slaveof�sz
Redis.slaveofcCs8dg}|dk	r|j|�|jjjdd�}|j|d|i�S)zw
        Get the entries from the slowlog. If ``num`` is specified, get the
        most recent ``num`` items.
        zSLOWLOG GETNr�F)rcrZconnection_kwargsr@rW)r6�numr#r�r$r$r%�slowlog_get�s
zRedis.slowlog_getcCs
|jd�S)z&Get the number of items in the slowlogzSLOWLOG LEN)rW)r6r$r$r%�slowlog_len�szRedis.slowlog_lencCs
|jd�S)zRemove all items in the slowlogz
SLOWLOG RESET)rW)r6r$r$r%�
slowlog_reset�szRedis.slowlog_resetcCs
|jd�S)z�
        Returns the server time as a 2-item tuple of ints:
        (seconds since epoch, microseconds into this second).
        r)rW)r6r$r$r%r;�sz
Redis.timecCs|jd||�S)z�
        Redis synchronous replication
        That returns the number of replicas that processed the query when
        we finally have at least ``num_replicas``, or when the ``timeout`` was
        reached.
        ZWAIT)rW)r6Znum_replicasr@r$r$r%�wait�sz
Redis.waitcCs|jd||�S)z�
        Appends the string ``value`` to the value at ``key``. If ``key``
        doesn't already exist, create it with a value of ``value``.
        Returns the new length of the value at ``key``.
        ZAPPEND)rW)r6rfrZr$r$r%rc�szRedis.appendcCsb|g}|dk	r,|dk	r,|j|�|j|�n(|dk	r<|dksL|dk	rT|dkrTtd��|jd|��S)z�
        Returns the count of set bits in the value of ``key``.  Optional
        ``start`` and ``end`` paramaters indicate which bytes to consider
        Nz$Both start and end must be specified�BITCOUNT)r�)rcrrW)r6rf�start�end�paramsr$r$r%�bitcount�s
zRedis.bitcountcCst|||d�S)z�
        Return a BitFieldOperation instance to conveniently construct one or
        more bitfield operations on ``key``.
        )�default_overflow)�BitFieldOperation)r6rfr�r$r$r%�bitfield�szRedis.bitfieldcGs|jd||f|��S)z|
        Perform a bitwise operation using ``operation`` between ``keys`` and
        store the result in ``dest``.
        ZBITOP)rW)r6Z	operation�destr"r$r$r%�bitop�szRedis.bitopcCsl|dkrtd��||g}|dk	o(|j|�|dk	rF|dk	rF|j|�n|dkr^|dk	r^td��|jd|��S)	a
        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.
        rrWzbit must be 0 or 1Nz0start argument is not set, when end is specified�BITPOS)rrW)r�)rrcrW)r6rf�bitr�r�r�r$r$r%�bitpos�szRedis.bitposrWcCs|j||�S)z�
        Decrements the value of ``key`` by ``amount``.  If no key exists,
        the value will be initialized as 0 - ``amount``
        )�decrby)r6r��amountr$r$r%�decr
sz
Redis.decrcCs|jd||�S)z�
        Decrements the value of ``key`` by ``amount``.  If no key exists,
        the value will be initialized as 0 - ``amount``
        ZDECRBY)rW)r6r�r�r$r$r%r�szRedis.decrbycGs|jd|��S)z.Delete one or more keys specified by ``names``�DEL)r�)rW)r6�namesr$r$r%�deleteszRedis.deletecCs|j|�dS)N)r�)r6r�r$r$r%r>!szRedis.__delitem__cCs|jd|�S)z�
        Return a serialized version of the value stored at the specified key.
        If key does not exist a nil bulk reply is returned.
        ZDUMP)rW)r6r�r$r$r%�dump$sz
Redis.dumpcGs|jd|��S)z*Returns the number of ``names`` that exist�EXISTS)r�)rW)r6r�r$r$r%�exists+szRedis.existscCs&t|tj�rt|j��}|jd||�S)z�
        Set an expire flag on key ``name`` for ``time`` seconds. ``time``
        can be represented by an integer or a Python timedelta object.
        ZEXPIRE)rr)�	timedeltar'�
total_secondsrW)r6r�r;r$r$r%�expire0szRedis.expirecCs,t|tj�rttj|j���}|jd||�S)z�
        Set an expire flag on key ``name``. ``when`` can be represented
        as an integer indicating unix time or a Python datetime object.
        ZEXPIREAT)rr)r'�mod_time�mktime�	timetuplerW)r6r��whenr$r$r%�expireat9szRedis.expireatcCs|jd|�S)zT
        Return the value at key ``name``, or None if the key doesn't exist
        �GET)rW)r6r�r$r$r%r@Bsz	Redis.getcCs"|j|�}|dk	r|St|��dS)zg
        Return the value at key ``name``, raises a KeyError if the key
        doesn't exist.
        N)r@�KeyError)r6r�rZr$r$r%r?Hs
zRedis.__getitem__cCs|jd||�S)z@Returns a boolean indicating the value of ``offset`` in ``name``ZGETBIT)rW)r6r��offsetr$r$r%�getbitRszRedis.getbitcCs|jd|||�S)z�
        Returns the substring of the string value stored at ``key``,
        determined by the offsets ``start`` and ``end`` (both are inclusive)
        ZGETRANGE)rW)r6rfr�r�r$r$r%�getrangeVszRedis.getrangecCs|jd||�S)z{
        Sets the value at key ``name`` to ``value``
        and returns the old value at key ``name`` atomically.
        ZGETSET)rW)r6r�rZr$r$r%�getset]szRedis.getsetcCs|j||�S)z�
        Increments the value of ``key`` by ``amount``.  If no key exists,
        the value will be initialized as ``amount``
        )�incrby)r6r�r�r$r$r%�incrdsz
Redis.incrcCs|jd||�S)z�
        Increments the value of ``key`` by ``amount``.  If no key exists,
        the value will be initialized as ``amount``
        �INCRBY)rW)r6r�r�r$r$r%r�kszRedis.incrby��?cCs|jd||�S)z�
        Increments the value at key ``name`` by floating ``amount``.
        If no key exists, the value will be initialized as ``amount``
        ZINCRBYFLOAT)rW)r6r�r�r$r$r%�incrbyfloattszRedis.incrbyfloatcCs|jd|�S)z+Returns a list of keys matching ``pattern``ZKEYS)rW)r6r�r$r$r%r"{sz
Redis.keyscGs*t||�}i}|sg|t<|jd|�|�S)zJ
        Returns a list of values ordered identically to ``keys``
        �MGET)r�)r&rrW)r6r"r#r�r$r$r%�mgets

z
Redis.mgetcCs.g}xt|�D]}|j|�qW|jd|��S)z�
        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().
        �MSET)r�)rr!rW)r6�mapping�itemsr�r$r$r%�mset�sz
Redis.msetcCs.g}xt|�D]}|j|�qW|jd|��S)a3
        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.
        �MSETNX)r�)rr!rW)r6r�r�r�r$r$r%�msetnx�szRedis.msetnxcCs|jd||�S)z;Moves the key ``name`` to a different Redis database ``db``ZMOVE)rW)r6r�rr$r$r%�move�sz
Redis.movecCs|jd|�S)z!Removes an expiration on ``name``ZPERSIST)rW)r6r�r$r$r%�persist�sz
Redis.persistcCs*t|tj�rt|j�d�}|jd||�S)z�
        Set an expire flag on key ``name`` for ``time`` milliseconds.
        ``time`` can be represented by an integer or a Python timedelta
        object.
        i�ZPEXPIRE)rr)r�r'r�rW)r6r�r;r$r$r%�pexpire�sz
Redis.pexpirecCsBt|tj�r4t|jd�}ttj|j���d|}|jd||�S)z�
        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.
        i�Z	PEXPIREAT)rr)r'Zmicrosecondr�r�r�rW)r6r�r�Zmsr$r$r%�	pexpireat�szRedis.pexpireatcCs,t|tj�rt|j�d�}|jd|||�S)z�
        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
        i�ZPSETEX)rr)r�r'r�rW)r6r�Ztime_msrZr$r$r%�psetex�szRedis.psetexcCs|jd|�S)zEReturns the number of milliseconds until the key ``name`` will expireZPTTL)rW)r6r�r$r$r%�pttl�sz
Redis.pttlcCs
|jd�S)z Returns the name of a random keyr�)rW)r6r$r$r%�	randomkey�szRedis.randomkeycCs|jd||�S)z/
        Rename key ``src`` to ``dst``
        ZRENAME)rW)r6�src�dstr$r$r%�rename�szRedis.renamecCs|jd||�S)z>Rename key ``src`` to ``dst`` if ``dst`` doesn't already existZRENAMENX)rW)r6r�r�r$r$r%�renamenx�szRedis.renamenxcCs&|||g}|r|jd�|jd|��S)zk
        Create a key using the provided serialized value, previously obtained
        using DUMP.
        ZREPLACE�RESTORE)r�)rcrW)r6r��ttlrZr�r�r$r$r%�restore�s

z
Redis.restorec	Cs�||g}|dk	r<|jd�t|tj�r2t|j��}|j|�|dk	rt|jd�t|tj�rjt|j�d�}|j|�|r�|jd�|r�|jd�|r�|jd�|jd	|��S)
a,
        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`` if set to True, set the value at key ``name`` to ``value`` only
            if it already exists.

        ``keepttl`` if True, retain the time to live associated with the key.
            (Available since Redis 6.0)
        NZEXZPXi�ZNXZXXZKEEPTTLr)r)rcrr)r�r'r�rW)	r6r�rZZexZpx�nx�xxZkeepttlr[r$r$r%r��s$






z	Redis.setcCs|j||�dS)N)r�)r6r�rZr$r$r%rBszRedis.__setitem__cCs|rdp
d}|jd|||�S)z�
        Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
        indicating the previous value of ``offset``.
        rWrZSETBIT)rW)r6r�r�rZr$r$r%�setbitszRedis.setbitcCs(t|tj�rt|j��}|jd|||�S)z�
        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.
        ZSETEX)rr)r�r'r�rW)r6r�r;rZr$r$r%�setexszRedis.setexcCs|jd||�S)z?Set the value of key ``name`` to ``value`` if key doesn't existZSETNX)rW)r6r�rZr$r$r%�setnx szRedis.setnxcCs|jd|||�S)a�
        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
        of what's being injected.

        Returns the length of the new string.
        ZSETRANGE)rW)r6r�r�rZr$r$r%�setrange$szRedis.setrangecCs|jd|�S)z:Return the number of bytes stored in the value of ``name``ZSTRLEN)rW)r6r�r$r$r%�strlen1szRedis.strlencCs|jd|||�S)z�
        Return a substring of the string at key ``name``. ``start`` and ``end``
        are 0-based integers specifying the portion of the string to return.
        ZSUBSTR)rW)r6r�r�r�r$r$r%�substr5szRedis.substrcGs|jd|��S)zs
        Alters the last access time of a key(s) ``*args``. A key is ignored
        if it does not exist.
        �TOUCH)r�)rW)r6r#r$r$r%�touch<szRedis.touchcCs|jd|�S)z@Returns the number of seconds until the key ``name`` will expireZTTL)rW)r6r�r$r$r%r�Csz	Redis.ttlcCs|jd|�S)z Returns the type of key ``name``ZTYPE)rW)r6r�r$r$r%r�Gsz
Redis.typecGstjtd��dS)zX
        Watches the values at keys ``names``, or None if the key doesn't exist
        z!Call WATCH from a Pipeline objectN)r%r&r')r6r�r$r$r%r9KszRedis.watchcCstjtd��dS)zW
        Unwatches the value at key ``name``, or None of the key doesn't exist
        z#Call UNWATCH from a Pipeline objectN)r%r&r')r6r$r$r%�unwatchQsz
Redis.unwatchcGs|jd|��S)z.Unlink one or more keys specified by ``names``�UNLINK)r�)rW)r6r�r$r$r%�unlinkXszRedis.unlinkcCs.|dkrd}t|d�}|j|�|jd|��S)a=
        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.
        Nr�BLPOP)r�)r&rcrW)r6r"r@r$r$r%�blpop]s


zRedis.blpopcCs.|dkrd}t|d�}|j|�|jd|��S)a=
        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.
        Nr�BRPOP)r)r&rcrW)r6r"r@r$r$r%�brpopns


zRedis.brpopcCs|dkrd}|jd|||�S)a
        Pop a value off the tail of ``src``, push it on the head of ``dst``
        and then return it.

        This command blocks until a value is in ``src`` or until ``timeout``
        seconds elapse, whichever is first. A ``timeout`` value of 0 blocks
        forever.
        NrZ
BRPOPLPUSH)rW)r6r�r�r@r$r$r%�
brpoplpushs	zRedis.brpoplpushcCs|jd||�S)z�
        Return the item from list ``name`` at position ``index``

        Negative indexes are supported and will return an item at the
        end of the list
        ZLINDEX)rW)r6r��indexr$r$r%�lindex�szRedis.lindexcCs|jd||||�S)z�
        Insert ``value`` in list ``name`` either immediately before or after
        [``where``] ``refvalue``

        Returns the new length of the list on success or -1 if ``refvalue``
        is not in the list.
        ZLINSERT)rW)r6r��whereZrefvaluerZr$r$r%�linsert�sz
Redis.linsertcCs|jd|�S)z&Return the length of the list ``name``ZLLEN)rW)r6r�r$r$r%�llen�sz
Redis.llencCs|jd|�S)z5Remove and return the first item of the list ``name``ZLPOP)rW)r6r�r$r$r%�lpop�sz
Redis.lpopcGs|jd|f|��S)z2Push ``values`` onto the head of the list ``name``ZLPUSH)rW)r6r�r�r$r$r%�lpush�szRedis.lpushcCs|jd||�S)zDPush ``value`` onto the head of the list ``name`` if ``name`` existsZLPUSHX)rW)r6r�rZr$r$r%�lpushx�szRedis.lpushxcCs|jd|||�S)z�
        Return a slice of the list ``name`` between
        position ``start`` and ``end``

        ``start`` and ``end`` can be negative numbers just like
        Python slicing notation
        ZLRANGE)rW)r6r�r�r�r$r$r%�lrange�szRedis.lrangecCs|jd|||�S)a�
        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 value moving from tail to head.
            count = 0: Remove all elements equal to value.
        ZLREM)rW)r6r��countrZr$r$r%�lrem�s
z
Redis.lremcCs|jd|||�S)z.Set ``position`` of list ``name`` to ``value``ZLSET)rW)r6r�rrZr$r$r%�lset�sz
Redis.lsetcCs|jd|||�S)z�
        Trim the list ``name``, removing all values not within the slice
        between ``start`` and ``end``

        ``start`` and ``end`` can be negative numbers just like
        Python slicing notation
        ZLTRIM)rW)r6r�r�r�r$r$r%�ltrim�szRedis.ltrimcCs|jd|�S)z4Remove and return the last item of the list ``name``ZRPOP)rW)r6r�r$r$r%�rpop�sz
Redis.rpopcCs|jd||�S)z�
        RPOP a value off of the ``src`` list and atomically LPUSH it
        on to the ``dst`` list.  Returns the value.
        Z	RPOPLPUSH)rW)r6r�r�r$r$r%�	rpoplpush�szRedis.rpoplpushcGs|jd|f|��S)z2Push ``values`` onto the tail of the list ``name``ZRPUSH)rW)r6r�r�r$r$r%�rpush�szRedis.rpushcCs|jd||�S)zDPush ``value`` onto the tail of the list ``name`` if ``name`` existsZRPUSHX)rW)r6r�rZr$r$r%�rpushx�szRedis.rpushxc

CsX|dk	r|dks |dk	r(|dkr(td��|g}
|dk	rJ|
jd�|
j|�|dk	rx|dk	rx|
jd�|
j|�|
j|�|dk	r�t|ttf�r�|
jd�|
j|�n"x |D]}|
jd�|
j|�q�W|r�|
jd�|r�|
jd�|dk	r�|
jd�|
j|�|	�r2|�s*t|ttf��s*t|�d	k�r2td
��d|	�rBt|�ndi}|jd
|
�|�S)a�
        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 items from external keys rather than the
            sorted data itself.  Use an "*" to indicate where in the key
            the item value is located

        ``desc`` allows for reversing the sort

        ``alpha`` allows for sorting lexicographically rather than numerically

        ``store`` allows for storing the result of the sort into
            the key ``store``

        ``groups`` if set to True and if ``get`` contains at least two
            elements, sort will return a list of tuples, each containing the
            values fetched from the arguments to ``get``.

        Nz,``start`` and ``num`` must both be specifiedsBYsLIMITsGETsDESCsALPHAsSTOREr�zVwhen using "groups" the "get" argument must be specified and contain at least two keysr�r�)r�)rrcrrr�lenrW)
r6r�r�r�Zbyr@�descZalphar�r�r[�gr�r$r$r%�sort�s<











&z
Redis.sortcCsV|g}|dk	r|jd|g�|dk	r2|jd|g�|dk	rH|jd|g�|jd|��S)a
        Incrementally return lists of key names. Also return a cursor
        indicating the scan position.

        ``match`` allows for filtering the keys by pattern

        ``count`` provides a hint to Redis about the number of keys to
            return per batch.

        ``_type`` filters the returned values by a particular Redis type.
            Stock Redis instances allow for the following types:
            HASH, LIST, SET, STREAM, STRING, ZSET
            Additionally, Redis modules can expose other types as well.
        NsMATCHsCOUNTsTYPEr�)r�)r!rW)r6r��matchr
r{r[r$r$r%�scan*sz
Redis.scanccs@d}x6|dkr:|j||||d�\}}x|D]
}|Vq*WqWdS)a*
        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`` provides a hint to Redis about the number of keys to
            return per batch.

        ``_type`` filters the returned values by a particular Redis type.
            Stock Redis instances allow for the following types:
            HASH, LIST, SET, STREAM, STRING, ZSET
            Additionally, Redis modules can expose other types as well.
        �0r)r�rr
r{N)r)r6rr
r{r�r7r[r$r$r%�	scan_iterBs

zRedis.scan_itercCsB||g}|dk	r|jd|g�|dk	r4|jd|g�|jd|��S)z�
        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
        NsMATCHsCOUNTr)r)r!rW)r6r�r�rr
r[r$r$r%�sscanXs	zRedis.sscanccs@d}x6|dkr:|j||||d�\}}x|D]
}|Vq*WqWdS)a
        Make an iterator using the SSCAN 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
        rr)r�rr
N)r)r6r�rr
r�r7r[r$r$r%�
sscan_iterhs	

zRedis.sscan_itercCsB||g}|dk	r|jd|g�|dk	r4|jd|g�|jd|��S)z�
        Incrementally return key/value slices in a hash. 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
        NsMATCHsCOUNTr�)r�)r!rW)r6r�r�rr
r[r$r$r%�hscanxs	zRedis.hscanccsDd}x:|dkr>|j||||d�\}}x|j�D]
}|Vq.WqWdS)a
        Make an iterator using the HSCAN 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
        rr)r�rr
N)rr�)r6r�rr
r�r7r[r$r$r%�
hscan_iter�s	
zRedis.hscan_itercCsL||g}|dk	r|jd|g�|dk	r4|jd|g�d|i}|jd|�|�S)aM
        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
        NsMATCHsCOUNTr�r)r)r!rW)r6r�r�rr
r�r[r�r$r$r%�zscan�szRedis.zscanccsBd}x8|dkr<|j|||||d�\}}x|D]
}|Vq,WqWdS)aL
        Make an iterator using the ZSCAN 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

        ``score_cast_func`` a callable used to cast the score return value
        rr)r�rr
r�N)r!)r6r�rr
r�r�r7r[r$r$r%�
zscan_iter�s


zRedis.zscan_itercGs|jd|f|��S)z Add ``value(s)`` to set ``name``ZSADD)rW)r6r�r�r$r$r%�sadd�sz
Redis.saddcCs|jd|�S)z-Return the number of elements in set ``name``ZSCARD)rW)r6r�r$r$r%�scard�szRedis.scardcGst||�}|jd|��S)z3Return the difference of sets specified by ``keys``�SDIFF)r%)r&rW)r6r"r#r$r$r%�sdiff�s
zRedis.sdiffcGst||�}|jd|f|��S)z�
        Store the difference of sets specified by ``keys`` into a new
        set named ``dest``.  Returns the number of keys in the new set.
        Z
SDIFFSTORE)r&rW)r6r�r"r#r$r$r%�
sdiffstore�s
zRedis.sdiffstorecGst||�}|jd|��S)z5Return the intersection of sets specified by ``keys``�SINTER)r()r&rW)r6r"r#r$r$r%�sinter�s
zRedis.sintercGst||�}|jd|f|��S)z�
        Store the intersection of sets specified by ``keys`` into a new
        set named ``dest``.  Returns the number of keys in the new set.
        ZSINTERSTORE)r&rW)r6r�r"r#r$r$r%�sinterstore�s
zRedis.sinterstorecCs|jd||�S)zDReturn a boolean indicating if ``value`` is a member of set ``name``Z	SISMEMBER)rW)r6r�rZr$r$r%�	sismember�szRedis.sismembercCs|jd|�S)z&Return all members of the set ``name``ZSMEMBERS)rW)r6r�r$r$r%�smembers�szRedis.smemberscCs|jd|||�S)z9Move ``value`` from set ``src`` to set ``dst`` atomicallyZSMOVE)rW)r6r�r�rZr$r$r%�smove�szRedis.smovecCs$|dk	r|gpg}|jd|f|��S)z1Remove and return a random member of set ``name``NZSPOP)rW)r6r�r
r#r$r$r%�spop�sz
Redis.spopcCs$|dk	r|gpg}|jd|f|��S)z�
        If ``number`` is None, returns a random member of set ``name``.

        If ``number`` is supplied, returns a list of ``number`` random
        members of set ``name``. Note this is only available when running
        Redis 2.6+.
        NZSRANDMEMBER)rW)r6r��numberr#r$r$r%�srandmember�szRedis.srandmembercGs|jd|f|��S)z#Remove ``values`` from set ``name``ZSREM)rW)r6r�r�r$r$r%�srem�sz
Redis.sremcGst||�}|jd|��S)z.Return the union of sets specified by ``keys``�SUNION)r2)r&rW)r6r"r#r$r$r%�sunion	s
zRedis.sunioncGst||�}|jd|f|��S)z�
        Store the union of sets specified by ``keys`` into a new
        set named ``dest``.  Returns the number of keys in the new set.
        ZSUNIONSTORE)r&rW)r6r�r"r#r$r$r%�sunionstore	s
zRedis.sunionstorecGs|jd||f|��S)z�
        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.
        ZXACK)rW)r6r��	groupname�idsr$r$r%�xack	sz
Redis.xackcCs�g}|dk	rRt|ttf�s$|dkr,td��|jd�|rD|jd�|jt|��|j|�t|t�stt|�dkr|td��xt|�D]}|j	|�q�W|j
d|f|��S)	aW
        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

        NrWz&XADD maxlen must be a positive integersMAXLEN�~rz$XADD fields must be a non-empty dictZXADD)rr'r
rrcryr,rrr!rW)r6r�Zfieldsr��maxlen�approximater[r�r$r$r%�xadd	s



z
Redis.xaddc
CsPt|ttf�s|dkr td��t|ttf�s6|r>td��i}|||t|�g}|jt|��|dk	r�t|ttf�s~td��|jdt|�f�|dk	r�t|ttf�s�td��|jdt|�f�|dk	r�t|ttf�s�td	��|jd
t|�f�|	�rt|	t��s
td��|j	d�|
�r@t|
t��s.td
��|j	d�d|d<|j
d|�|�S)a�
        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: optional. Set the idle time (last time it was delivered) of the
         message in ms
        time: optional integer. This is the same as idle but instead of a
         relative amount of milliseconds, it sets the idle time to a specific
         Unix time (in milliseconds).
        retrycount: optional integer. set the retry counter to the specified
         value. This counter is incremented every time a message is delivered
         again.
        force: optional boolean, false by default. Creates the pending message
         entry in the PEL even if certain specified IDs are not already in the
         PEL assigned to a different client.
        justid: optional boolean, false by default. Return just an array of IDs
         of messages successfully claimed, without returning the actual message
        rz3XCLAIM min_idle_time must be a non negative integerzLXCLAIM message_ids must be a non empty list or tuple of message IDs to claimNzXCLAIM idle must be an integersIDLEzXCLAIM time must be an integersTIMEz$XCLAIM retrycount must be an integers
RETRYCOUNTzXCLAIM force must be a booleansFORCEzXCLAIM justid must be a booleansJUSTIDTr�r)r)rr'r
rrr�ryr!r�rcrW)
r6r�r5�consumernameZ
min_idle_timeZmessage_idsZidler;Z
retrycountreZjustidrkr[r$r$r%�xclaim3	s:

zRedis.xclaimcGs|jd|f|��S)z�
        Deletes one or more messages from a stream.
        name: name of the stream.
        *ids: message ids to delete.
        ZXDEL)rW)r6r�r6r$r$r%�xdelo	sz
Redis.xdel�$cCs$d|||g}|r|jd�|j|�S)z�
        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.
        z
XGROUP CREATEsMKSTREAM)rcrW)r6r�r5r�Zmkstreamr[r$r$r%�
xgroup_createw	s
zRedis.xgroup_createcCs|jd|||�S)a)
        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
        zXGROUP DELCONSUMER)rW)r6r�r5r<r$r$r%�xgroup_delconsumer�	s	
zRedis.xgroup_delconsumercCs|jd||�S)z|
        Destroy a consumer group.
        name: name of the stream.
        groupname: name of the consumer group.
        zXGROUP DESTROY)rW)r6r�r5r$r$r%�xgroup_destroy�	szRedis.xgroup_destroycCs|jd|||�S)z�
        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.
        zXGROUP SETID)rW)r6r�r5r�r$r$r%�xgroup_setid�	szRedis.xgroup_setidcCs|jd||�S)z�
        Returns general information about the consumers in the group.
        name: name of the stream.
        groupname: name of the consumer group.
        zXINFO CONSUMERS)rW)r6r�r5r$r$r%�xinfo_consumers�	szRedis.xinfo_consumerscCs|jd|�S)zx
        Returns general information about the consumer groups of the stream.
        name: name of the stream.
        zXINFO GROUPS)rW)r6r�r$r$r%�xinfo_groups�	szRedis.xinfo_groupscCs|jd|�S)za
        Returns general information about the stream.
        name: name of the stream.
        zXINFO STREAM)rW)r6r�r$r$r%�xinfo_stream�	szRedis.xinfo_streamcCs|jd|�S)zC
        Returns the number of elements in a given stream.
        ZXLEN)rW)r6r�r$r$r%�xlen�	sz
Redis.xlencCs|jd||�S)z�
        Returns information about pending messages of a group.
        name: name of the stream.
        groupname: name of the consumer group.
        r)rW)r6r�r5r$r$r%�xpending�	szRedis.xpendingcCs�||g}|dk	s |dk	s |dk	rt|dks8|dks8|dkr@td��t|ttf�sX|d	kr`td��|j||t|�f�|dk	r�|dks�|dks�|dkr�td��|j|�|jd
|�ddi�S)aH
        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).
        NzOXPENDING must be provided with min, max and count parameters, or none of them. rWz&XPENDING count must be a integer >= -1zaif XPENDING is provided with consumername, it must be provided with min, max and count parametersrr�Tr^)r)rrr'r
r!ryrcrW)r6r�r5r�r�r
r<r[r$r$r%�xpending_range�	s
zRedis.xpending_ranger��+cCsZ||g}|dk	rHt|ttf�s(|dkr0td��|jd�|jt|��|jd|f|��S)a�
        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.
        NrWz'XRANGE count must be a positive integersCOUNTZXRANGE)rr'r
rrcryrW)r6r�r�r�r
r[r$r$r%�xrange�	s
zRedis.xrangecCs�g}|dk	rDt|ttf�s$|dkr,td��|jd�|jt|��|dk	r�t|ttf�sd|dkrltd��|jd�|jt|��t|t�s�t|�dkr�td��|jd	�tt	|��\}}|j
|�|j
|�|jd|��S)an
        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.
        Nrz*XREAD block must be a non-negative integersBLOCKrWz&XREAD count must be a positive integersCOUNTz&XREAD streams must be a non empty dictsSTREAMS�XREAD)rL)rr'r
rrcryr,rr	rr!rW)r6�streamsr
�blockr[r"r�r$r$r%�xread�	s$	




zRedis.xreadcCs�d||g}|dk	rJt|ttf�s*|dkr2td��|jd�|jt|��|dk	r�t|ttf�sj|dkrrtd��|jd�|jt|��|r�|jd	�t|t�s�t|�dkr�td
��|jd�|j|j	��|j|j
��|jd
|��S)a�
        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 milliseconds to wait, if nothing already present.
        noack: do not add messages to the PEL
        sGROUPNrWz+XREADGROUP count must be a positive integersCOUNTrz/XREADGROUP block must be a non-negative integersBLOCKsNOACKz+XREADGROUP streams must be a non empty dictsSTREAMS�
XREADGROUP)rP)rr'r
rrcryr,rr!r"r�rW)r6r5r<rMr
rNZnoackr[r$r$r%�
xreadgroup
s&




zRedis.xreadgroupcCsZ||g}|dk	rHt|ttf�s(|dkr0td��|jd�|jt|��|jd|f|��S)a�
        Read stream values within an interval, in reverse order.
        name: name of the stream
        start: first stream ID. defaults to '+',
               meaning the latest available.
        finish: last stream ID. defaults to '-',
                meaning the earliest available.
        count: if set, only return this many items, beginning with the
               latest available.
        NrWz*XREVRANGE count must be a positive integersCOUNTZ	XREVRANGE)rr'r
rrcryrW)r6r�r�r�r
r[r$r$r%�	xrevrange1
s
zRedis.xrevrangecCs0dg}|r|jd�|j|�|jd|f|��S)z�
        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
        sMAXLENr8ZXTRIM)rcrW)r6r�r9r:r[r$r$r%�xtrimE
s


zRedis.xtrimc
Cs�|std��|r|rtd��|r4t|�dkr4td��g}i}|rJ|jd�|rX|jd�|rf|jd�|r||jd�d	|d
<x,t|�D] }	|j|	d�|j|	d�q�W|jd|f|�|�S)
a
        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 elements that already
        exist. New elements will not be added.

        ``ch`` modifies the return value to be the numbers of elements changed.
        Changed elements include new elements that were added and elements
        whose scores changed.

        ``incr`` modifies ZADD to behave like ZINCRBY. In this mode only a
        single element/score pair can be specified and the score is the amount
        the existing score will be incremented by. When using this mode the
        return value of ZADD will be the new score of the element.

        The return value of ZADD varies based on the mode specified. With no
        options, ZADD returns the number of new elements added to the sorted
        set.
        z-ZADD requires at least one element/score pairz)ZADD allows either 'nx' or 'xx', not bothrWzFZADD option 'incr' only works when passing a single element/score pairsNXsXXsCHsINCRTr�rr)rrrcrrW)
r6r�r�r�r�Zchr�r[r�r�r$r$r%�zaddS
s*



z
Redis.zaddcCs|jd|�S)z8Return the number of elements in the sorted set ``name``ZZCARD)rW)r6r�r$r$r%�zcard�
szRedis.zcardcCs|jd|||�S)z�
        Returns the number of elements in the sorted set at key ``name`` with
        a score between ``min`` and ``max``.
        ZZCOUNT)rW)r6r�r�r�r$r$r%�zcount�
szRedis.zcountcCs|jd|||�S)zEIncrement the score of ``value`` in sorted set ``name`` by ``amount``ZZINCRBY)rW)r6r�r�rZr$r$r%�zincrby�
sz
Redis.zincrbycCs|jd|||�S)z�
        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.
        ZZINTERSTORE)�_zaggregate)r6r�r"�	aggregater$r$r%�zinterstore�
szRedis.zinterstorecCs|jd|||�S)z�
        Return the number of items in the sorted set ``name`` between the
        lexicographical range ``min`` and ``max``.
        Z	ZLEXCOUNT)rW)r6r�r�r�r$r$r%�	zlexcount�
szRedis.zlexcountcCs.|dk	r|gpg}ddi}|jd|f|�|�S)zy
        Remove and return up to ``count`` members with the highest scores
        from the sorted set ``name``.
        Nr�TZZPOPMAX)rW)r6r�r
r#r�r$r$r%�zpopmax�
sz
Redis.zpopmaxcCs.|dk	r|gpg}ddi}|jd|f|�|�S)zx
        Remove and return up to ``count`` members with the lowest scores
        from the sorted set ``name``.
        Nr�TZZPOPMIN)rW)r6r�r
r#r�r$r$r%�zpopmin�
sz
Redis.zpopmincCs.|dkrd}t|d�}|j|�|jd|��S)aR
        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.
        Nr�BZPOPMAX)r^)r&rcrW)r6r"r@r$r$r%�bzpopmax�
s


zRedis.bzpopmaxcCs.|dkrd}t|d�}|j|�|jd|��S)aR
        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.
        Nr�BZPOPMIN)r`)r&rcrW)r6r"r@r$r$r%�bzpopmin�
s


zRedis.bzpopminc	CsF|r|j|||||�Sd|||g}|r0|jd�||d�}|j||�S)a�
        Return a range of values from sorted set ``name`` between
        ``start`` and ``end`` sorted in ascending order.

        ``start`` and ``end`` can be negative, indicating the end of the range.

        ``desc`` a boolean indicating whether to sort the results descendingly

        ``withscores`` indicates to return the scores along with the values.
        The return type is a list of (value, score) pairs

        ``score_cast_func`` a callable used to cast the score return value
        ZZRANGEs
WITHSCORES)r�r�)�	zrevrangercrW)	r6r�r�r�rr�r�r[r�r$r$r%�zrange�
s
zRedis.zrangecCs^|dk	r|dks |dk	r(|dkr(td��d|||g}|dk	rT|dk	rT|jd||g�|j|�S)z�
        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.
        Nz,``start`` and ``num`` must both be specifiedZZRANGEBYLEXsLIMIT)rr!rW)r6r�r�r�r�r�r[r$r$r%�zrangebylex�
szRedis.zrangebylexcCs^|dk	r|dks |dk	r(|dkr(td��d|||g}|dk	rT|dk	rT|jd||g�|j|�S)z�
        Return the reversed lexicographical range of values from sorted set
        ``name`` between ``max`` and ``min``.

        If ``start`` and ``num`` are specified, then return a slice of the
        range.
        Nz,``start`` and ``num`` must both be specifiedZZREVRANGEBYLEXsLIMIT)rr!rW)r6r�r�r�r�r�r[r$r$r%�zrevrangebylexszRedis.zrevrangebylexc
Csx|dk	r|dks |dk	r(|dkr(td��d|||g}|dk	rT|dk	rT|jd||g�|rb|jd�||d�}	|j||	�S)a�
        Return a range of values from the sorted set ``name`` with scores
        between ``min`` and ``max``.

        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 list of (value, score) pairs

        `score_cast_func`` a callable used to cast the score return value
        Nz,``start`` and ``num`` must both be specifiedZ
ZRANGEBYSCOREsLIMITs
WITHSCORES)r�r�)rr!rcrW)
r6r�r�r�r�r�r�r�r[r�r$r$r%�
zrangebyscores
zRedis.zrangebyscorecCs|jd||�S)zi
        Returns a 0-based value indicating the rank of ``value`` in sorted set
        ``name``
        ZZRANK)rW)r6r�rZr$r$r%�zrank/szRedis.zrankcGs|jd|f|��S)z1Remove member ``values`` from sorted set ``name``ZZREM)rW)r6r�r�r$r$r%�zrem6sz
Redis.zremcCs|jd|||�S)z�
        Remove all elements in the sorted set ``name`` between the
        lexicographical range specified by ``min`` and ``max``.

        Returns the number of elements removed.
        ZZREMRANGEBYLEX)rW)r6r�r�r�r$r$r%�zremrangebylex:szRedis.zremrangebylexcCs|jd|||�S)a
        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
        ZZREMRANGEBYRANK)rW)r6r�r�r�r$r$r%�zremrangebyrankCszRedis.zremrangebyrankcCs|jd|||�S)z�
        Remove all elements in the sorted set ``name`` with scores
        between ``min`` and ``max``. Returns the number of elements removed.
        ZZREMRANGEBYSCORE)rW)r6r�r�r�r$r$r%�zremrangebyscoreLszRedis.zremrangebyscorecCs0d|||g}|r|jd�||d�}|j||�S)a�
        Return a range of values from sorted set ``name`` between
        ``start`` and ``end`` sorted in descending order.

        ``start`` and ``end`` can be negative, indicating the end of the range.

        ``withscores`` indicates to return the scores along with the values
        The return type is a list of (value, score) pairs

        ``score_cast_func`` a callable used to cast the score return value
        Z	ZREVRANGEs
WITHSCORES)r�r�)rcrW)r6r�r�r�r�r�r[r�r$r$r%rbSs

zRedis.zrevrangec
Csx|dk	r|dks |dk	r(|dkr(td��d|||g}|dk	rT|dk	rT|jd||g�|rb|jd�||d�}	|j||	�S)a�
        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 list of (value, score) pairs

        ``score_cast_func`` a callable used to cast the score return value
        Nz,``start`` and ``num`` must both be specifiedZZREVRANGEBYSCOREsLIMITs
WITHSCORES)r�r�)rr!rcrW)
r6r�r�r�r�r�r�r�r[r�r$r$r%�zrevrangebyscoreis
zRedis.zrevrangebyscorecCs|jd||�S)zt
        Returns a 0-based value indicating the descending rank of
        ``value`` in sorted set ``name``
        ZZREVRANK)rW)r6r�rZr$r$r%�zrevrank�szRedis.zrevrankcCs|jd||�S)z<Return the score of element ``value`` in sorted set ``name``ZZSCORE)rW)r6r�rZr$r$r%�zscore�szRedis.zscorecCs|jd|||�S)z�
        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.
        ZZUNIONSTORE)rX)r6r�r"rYr$r$r%�zunionstore�szRedis.zunionstorecCst||t|�g}t|t�r,t|�t|�}}nd}|j|�|rR|jd�|j|�|rj|jd�|j|�|j|�S)NsWEIGHTSs	AGGREGATE)rrr,rrr!rcrW)r6r�r�r"rYr[Zweightsr$r$r%rX�s





zRedis._zaggregatecGs|jd|f|��S)z9Adds the specified elements to the specified HyperLogLog.ZPFADD)rW)r6r�r�r$r$r%�pfadd�szRedis.pfaddcGs|jd|��S)zo
        Return the approximated cardinality of
        the set observed by the HyperLogLog at key(s).
        �PFCOUNT)rq)rW)r6�sourcesr$r$r%�pfcount�sz
Redis.pfcountcGs|jd|f|��S)z1Merge N different HyperLogLogs into a single one.ZPFMERGE)rW)r6r�rrr$r$r%�pfmerge�sz
Redis.pfmergecGs|jd|f|��S)z"Delete ``keys`` from hash ``name``ZHDEL)rW)r6r�r"r$r$r%�hdel�sz
Redis.hdelcCs|jd||�S)zCReturns a boolean indicating if ``key`` exists within hash ``name``ZHEXISTS)rW)r6r�rfr$r$r%�hexists�sz
Redis.hexistscCs|jd||�S)z4Return the value of ``key`` within the hash ``name``ZHGET)rW)r6r�rfr$r$r%�hget�sz
Redis.hgetcCs|jd|�S)z3Return a Python dict of the hash's name/value pairsr�)rW)r6r�r$r$r%�hgetall�sz
Redis.hgetallcCs|jd|||�S)z=Increment the value of ``key`` in hash ``name`` by ``amount``ZHINCRBY)rW)r6r�rfr�r$r$r%�hincrby�sz
Redis.hincrbycCs|jd|||�S)zX
        Increment the value of ``key`` in hash ``name`` by floating ``amount``
        ZHINCRBYFLOAT)rW)r6r�rfr�r$r$r%�hincrbyfloat�szRedis.hincrbyfloatcCs|jd|�S)z,Return the list of keys within hash ``name``ZHKEYS)rW)r6r�r$r$r%�hkeys�szRedis.hkeyscCs|jd|�S)z.Return the number of elements in hash ``name``ZHLEN)rW)r6r�r$r$r%�hlen�sz
Redis.hlencCsb|dkr|rtd��g}|dk	r0|j||f�|rPx|j�D]}|j|�q>W|jd|f|��S)z�
        Set ``key`` to ``value`` within hash ``name``,
        ``mapping`` accepts a dict of key/value pairs that that will be
        added to hash ``name``.
        Returns the number of fields that were added.
        Nz'hset' with no key value pairsZHSET)rr!r�rW)r6r�rfrZr�r�r�r$r$r%�hset�sz
Redis.hsetcCs|jd|||�S)z�
        Set ``key`` to ``value`` within hash ``name`` if ``key`` does not
        exist.  Returns 1 if HSETNX created a field, otherwise 0.
        ZHSETNX)rW)r6r�rfrZr$r$r%�hsetnx�szRedis.hsetnxcCs^tjd|jj|jjftdd�|s,td��g}xt|�D]}|j|�q:W|jd|f|��S)z
        Set key to value within hash ``name`` for each corresponding
        key and value from the ``mapping`` dict.
        z0%s.hmset() is deprecated. Use %s.hset() instead.r�)�
stacklevelz"'hmset' with 'mapping' of length 0ZHMSET)	r%r&r=rCr'rrr!rW)r6r�r�r�r�r$r$r%�hmset�szRedis.hmsetcGst||�}|jd|f|��S)z8Returns a list of values ordered identically to ``keys``ZHMGET)r&rW)r6r�r"r#r$r$r%�hmgets
zRedis.hmgetcCs|jd|�S)z.Return the list of values within hash ``name``ZHVALS)rW)r6r�r$r$r%�hvals
szRedis.hvalscCs|jd||�S)zh
        Return the number of bytes stored in the value of ``key``
        within hash ``name``
        ZHSTRLEN)rW)r6r�rfr$r$r%�hstrlensz
Redis.hstrlencCs|jd||�S)z}
        Publish ``message`` on ``channel``.
        Returns the number of subscribers the message was delivered to.
        ZPUBLISH)rW)r6�channel�messager$r$r%�publishsz
Redis.publishcCs|jd|�S)zM
        Return a list of channels that have at least one subscriber
        zPUBSUB CHANNELS)rW)r6r�r$r$r%�pubsub_channelsszRedis.pubsub_channelscCs
|jd�S)zA
        Returns the number of subscriptions to patterns
        z
PUBSUB NUMPAT)rW)r6r$r$r%�
pubsub_numpat"szRedis.pubsub_numpatcGs|jd|��S)zv
        Return a list of (channel, number of subscribers) tuples
        for each channel given in ``*args``
        �
PUBSUB NUMSUB)r�)rW)r6r#r$r$r%�
pubsub_numsub(szRedis.pubsub_numsubcGs|jd|j�f|��S)Nz
CLUSTER %s)rWr5)r6Zcluster_argr#r$r$r%�cluster/sz
Redis.clustercGs|jd||f|��S)aP
        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.
        ZEVAL)rW)r6�script�numkeys�
keys_and_argsr$r$r%�eval2s	z
Redis.evalcGs|jd||f|��S)a�
        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``. This
        function exists purely for Redis API completion.
        ZEVALSHA)rW)r6�shar�r�r$r$r%�evalsha=s
z
Redis.evalshacGs|jd|��S)z�
        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 EXISTS)r�)rW)r6r#r$r$r%�
script_existsIszRedis.script_existscCs
|jd�S)z'Flush all scripts from the script cachezSCRIPT FLUSH)rW)r6r$r$r%�script_flushQszRedis.script_flushcCs
|jd�S)z'Kill the currently executing Lua scriptzSCRIPT KILL)rW)r6r$r$r%�script_killUszRedis.script_killcCs|jd|�S)z=Load a Lua ``script`` into the script cache. Returns the SHA.zSCRIPT LOAD)rW)r6r�r$r$r%�script_loadYszRedis.script_loadcCs
t||�S)a
        Register a Lua ``script`` specifying the ``keys`` it 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.
        )�Script)r6r�r$r$r%�register_script]szRedis.register_scriptcGs*t|�ddkrtd��|jd|f|��S)a
        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.
        r�rz4GEOADD requires places with lon, lat and name valuesZGEOADD)rrrW)r6r�r�r$r$r%�geoaddgszRedis.geoaddcCs<|||g}|r |dkr td��n|r.|j|�|jd|��S)	z�
        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.
        �m�km�mi�ftzGEODIST invalid unit�GEODIST)r�r�r�r�)r�)rrcrW)r6r�Zplace1Zplace2�unitr[r$r$r%�geodistss


z
Redis.geodistcGs|jd|f|��S)z�
        Return the geo hash string for each item of ``values`` members of
        the specified key identified by the ``name`` argument.
        r�)rW)r6r�r�r$r$r%�geohash�sz
Redis.geohashcGs|jd|f|��S)z�
        Return the positions of each item of ``values`` as members of
        the specified key identified by the ``name`` argument. Each position
        is represented by the pairs lon and lat.
        r�)rW)r6r�r�r$r$r%�geopos�szRedis.geoposc

Cs$|jd|||||||||	|
||d�
S)a�
        Return the members of the specified key identified by the
        ``name`` argument which are within the borders of the area specified
        with the ``latitude`` and ``longitude`` location and the maximum
        distance from the center specified by the ``radius`` value.

        The units must be one of the following : m, km mi, ft. By default

        ``withdist`` indicates to return the distances of each place.

        ``withcoord`` indicates to return the latitude and longitude of
        each place.

        ``withhash`` indicates to return the geohash string of each place.

        ``count`` indicates to return the number of elements up to N.

        ``sort`` indicates to return the places in a sorted way, ASC for
        nearest to fairest and DESC for fairest to nearest.

        ``store`` indicates to save the places names in a sorted set named
        with a specific key, each element of the destination sorted set is
        populated with the score got from the original geo sorted set.

        ``store_dist`` indicates to save the places names in a sorted set
        named with a specific key, instead of ``store`` the sorted set
        destination score is set with the distance.
        r�)r�r�r�r�r
rr�r�)�_georadiusgeneric)
r6r�Z	longitudeZlatitude�radiusr�r�r�r�r
rr�r�r$r$r%�	georadius�szRedis.georadiuscCs"|jd|||||||||	|
|d�S)a3
        This command is exactly like ``georadius`` with the sole difference
        that instead of taking, as the center of the area to query, a longitude
        and latitude value, it takes the name of a member already existing
        inside the geospatial index represented by the sorted set.
        r�)r�r�r�r�r
rr�r�)r�)r6r��memberr�r�r�r�r�r
rr�r�r$r$r%�georadiusbymember�s	zRedis.georadiusbymembercOs(t|�}|dr&|ddkr&td��n"|dr>|j|d�n
|jd�x"dD]\}}||rN|j|�qNW|d
r�|jd|d
g�|dr�|ddkr�|jd�n |ddkr�|jd�ntd��|dr�|dr�td��|d�r�|jd|dg�|d�r|jd|dg�|j|f|�|�S)Nr�r�r�r�r�zGEORADIUS invalid unitr��WITHDISTr��	WITHCOORDr��WITHHASHr
sCOUNTrZASCsASCZDESCsDESCzGEORADIUS invalid sortr�r�z3GEORADIUS store and store_dist cant be set togethersSTOREs	STOREDIST)r�r�r�r��r�r��r�r��r�r�)r�r�r�)rrrcr!rW)r6r�r#rkr[Zarg_nameZ	byte_reprr$r$r%r��s6



zRedis._georadiusgeneric)N)rrrNNNNNNNr
rNNFFFNNrNFNFrNN)TN)Nr?NNT)N)
FFNNNNNFFF)NNNN)N)F)r�)F)F)N)FFN)N)FF)NN)N)NN)N)NN)rW)rW)rW)rW)r�)r�)F)NNFFFr^)r^)r)r)r)NNNNFFNF)rNNN)NNN)rNN)NN)rNN)NN)N)N)r�NT)NNNFF)r?F)N)r�rJN)NN)NNF)rJr�N)T)FFFF)N)N)N)r)r)NN)NN)N)N)rW)r�)NNN)r�)N)NFFFNNNN)NFFFNNNN( rCrDrErFr3r0r�r'rXr�r�r�r�rQr�r�rr�r�r�r�r�r�rOr�r�rgr+rlrSr�r�r�r�r�r�r�r�r�r�r�r�r�r*�classmethodr	r:r0r1r5r3rCrErGrHrIrNrOrJrWrSr\r]r^r_r`rarbrnrorprqrrrsr}rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rdr�r�r�r�r�r�r�r�ryr�r�r�r�r�r�r�r�r�r�r�r�r�r;r�rcr�r�r�r�r�r�r�r>r�r�r<r�r�r@r?r�r�r�r�r�r�r"r�r�r�r�r�r�r�r�r�r�r�r�r�r�rBr�r�r�r�r�r�r�r�r�r9r�r�rrrrrrr	r
rrrrrrrrrrrrrrrr r!r"r#r$r&r'r)r*r+r,r-r.r0r1r3r4r7r;r=r>r@rArBrCrDrErFrGrHrIrKrOrQrRrSrTrUrVrWrZr[r\r]r_rarcrdrerfrgrhrirjrkrbrlrmrnrorXrprsrtrurvrwrxryrzr{r|r}r~r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r$r$r$r%r�s	
$:2		"	"

			
	



'


	


C		:		!/		
$r�c@sLeZdZdZejd�Zejd�Zdd�Zdd�Z	dd	�Z
d
d�Zdd
�ZdS)rFz�
    Monitor is useful for handling the MONITOR command to the redis server.
    next_command() method returns one command from monitor
    listen() method yields commands from monitor.
    z\[(\d+) (.*)\] (.*)z"(.*?)(?<!\\)"cCs||_|jjd�|_dS)N�MONITOR)rr)r()r6rr$r$r%r:�szMonitor.__init__cCs.|jjd�|jj�}t|�s*td|��|S)Nr�zMONITOR failed: %s)r(rRrXr�r)r6r*r$r$r%rI�s

zMonitor.__enter__cGs|jj�|jj|j�dS)N)r(rTrrP)r6r#r$r$r%rN
s
zMonitor.__exit__cCs�|jj�}t|t�r&|jjj|dd�}|jdd�\}}|jj|�}|j	�\}}}dj
|jj|��}|j
dd�j
dd�}|d	kr�d	}d
}	d	}
n4|jd�r�d}|dd
�}	d}
n|jdd�\}}	d}
t|�t|�||	|
|d�S)z)Parse the response from a monitor commandT)rer�rWz\"�"z\\�\Zluar�Zunix�NrHZtcp)r;r�client_address�client_port�client_typer�)r(rXrrrlrjr.�
monitor_rerr�r��
command_re�findallr�r`rYrXr')r6r*Zcommand_timeZcommand_datar�Zdb_idZclient_infor�r�r�r�r$r$r%�next_command

s0


zMonitor.next_commandccsx|j�VqWdS)z)Listen for commands coming to the server.N)r�)r6r$r$r%�listen*
szMonitor.listenN)
rCrDrErF�re�compiler�r�r:rIrNr�r�r$r$r$r%rF�s

 rFc@s�eZdZdZd7Zd8ZdZd9d	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
edd��Zdd�Zdd�Zd:dd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd;d/d0�Zd<d1d2�Zd=d3d4�Zd>d5d6�ZdS)?rDa*
    PubSub provides publish, subscribe and listen support to Redis channels.

    After subscribing to one or more channels, the listen() method will block
    until a message arrives on one of the subscribed channels. That message
    will be returned and it's safe to start listening again.
    r��pmessage�unsubscribe�punsubscribezredis-py-health-checkNFcCsZ||_||_||_d|_|jj�|_|jjr:d|jg|_nd|jj	|j�g|_|j
�dS)Nr�spong)rr4�ignore_subscribe_messagesr(rgrlr��HEALTH_CHECK_MESSAGE�health_check_responserirk)r6rr4r�r$r$r%r:<
szPubSub.__init__cCs|S)Nr$)r6r$r$r%rIN
szPubSub.__enter__cCs|j�dS)N)rk)r6rKrLrMr$r$r%rNQ
szPubSub.__exit__cCs&y|j�Wntk
r YnXdS)N)rkr�)r6r$r$r%rOT
szPubSub.__del__cCsN|jr.|jj�|jj�|jj|j�d|_i|_t�|_i|_t�|_	dS)N)
r(rTZclear_connect_callbacksrrP�channelsr��pending_unsubscribe_channels�patterns�pending_unsubscribe_patterns)r6r$r$r%rk]
s

zPubSub.resetcCs|j�dS)N)rk)r6r$r$r%rJh
szPubSub.closecCs�|jj�|jj�|jrVi}x*t|j�D]\}}|||jj|dd�<q*W|jf|�|jr�i}x*t|j�D]\}}|||jj|dd�<qlW|j	f|�dS)zBRe-subscribe to any channels and patterns previously subscribed toT)reN)
r��clearr�r�rrlrj�	subscriber��
psubscribe)r6r(r�r8r9r�r$r$r%�
on_connectk
s

zPubSub.on_connectcCst|jp|j�S)z@Indicates if there are subscriptions to any channels or patterns)r�r�r�)r6r$r$r%�
subscribed}
szPubSub.subscribedcGsV|jdkr*|jjd|j�|_|jj|j�|j}d|ji}|j||jf|�|�dS)z#Execute a publish/subscribe commandNrE�check_health)	r(rr)r4Zregister_connect_callbackr�r��_executerR)r6r#r(rkr$r$r%rW�
s

zPubSub.execute_commandcOs\y
|||�Sttfk
rV}z,|j�|jo6t|t�s:�|j�|||�Sd}~XnXdS)N)rrrTrrZconnect)r6r(r�r#rkrVr$r$r%r��
s

zPubSub._executeTrcCs\|j}|dkrtd��|j�|r6|j|d�r6dS|j||j�}|jrX||jkrXdS|S)z3Parse the response from a publish/subscribe commandNzNpubsub connection not set: did you forget to call subscribe() or psubscribe()?)r@)r(�RuntimeErrorr�Zcan_readr�rXrr�)r6rNr@rQr*r$r$r%rS�
s
zPubSub.parse_responsecCs@|j}|dkrtd��|jr<tj�|jkr<|jd|jdd�dS)NzNpubsub connection not set: did you forget to call subscribe() or psubscribe()?r�F)r�)r(r�rr;Znext_health_checkrRr�)r6rQr$r$r%r��
s
zPubSub.check_healthcs(|jj�|jj���fdd�t|�D�S)z�
        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.
        csi|]\}}|��|���qSr$r$)rIr8r9)rjrir$r%�
<dictcomp>�
sz*PubSub._normalize_keys.<locals>.<dictcomp>)rlrirjr)r6r7r$)rjrir%�_normalize_keys�
szPubSub._normalize_keyscOsf|rt|d|dd��}tj|�}|j|�|jdt|���}|j|�}|jj|�|jj	|�|S)aE
        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()``.
        rrWN�
PSUBSCRIBE)r�)
r&r,r-r1rWrr�r�r��difference_update)r6r#rkZnew_patterns�ret_valr$r$r%r��
s


zPubSub.psubscribecGsL|r,t|d|dd��}|jtj|��}n|j}|jj|�|jd|��S)zj
        Unsubscribe from the supplied patterns. If empty, unsubscribe from
        all patterns.
        rrWN�PUNSUBSCRIBE)r�)r&r�r,r-r�r�r1rW)r6r#r�r$r$r%r��
szPubSub.punsubscribecOsf|rt|d|dd��}tj|�}|j|�|jdt|���}|j|�}|jj|�|jj	|�|S)aR
        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()``.
        rrWN�	SUBSCRIBE)r�)
r&r,r-r1rWrr�r�r�r�)r6r#rkZnew_channelsr�r$r$r%r��
s


zPubSub.subscribecGsL|r,t|d|dd��}|jtj|��}n|j}|jj|�|jd|��S)zi
        Unsubscribe from the supplied channels. If empty, unsubscribe from
        all channels
        rrWN�UNSUBSCRIBE)r�)r&r�r,r-r�r�r1rW)r6r#r�r$r$r%r�szPubSub.unsubscribeccs0x*|jr*|j|jdd��}|dk	r|VqWdS)zBListen for messages on channels this client has been subscribed toT)rNN)r��handle_messagerS)r6r*r$r$r%r�sz
PubSub.listencCs"|jd|d�}|r|j||�SdS)z�
        Get the next message if one is available, otherwise None.

        If timeout is specified, the system will wait for `timeout` seconds
        before returning. Timeout should be specified as a floating point
        number.
        F)rNr@N)rSr�)r6r�r@r*r$r$r%�get_messageszPubSub.get_messagecCs|dkrdn|}|jd|�S)z'
        Ping the Redis server
        Nr�r�)rW)r6r�r$r$r%r�&szPubSub.pingcCs<t|d�}|dkr0||d|d|dd�}n2|dkrL|dd|dd�}n|d|d|dd�}||jkr�|d	kr�|d}||jkr�|jj|�|jj|d�n,|d}||jkr�|jj|�|jj|d�||jk�r|dkr�|jj	|d
d�}n|jj	|dd�}|�r8||�dSn|dk�r8|�s4|j
�r8dS|S)z�
        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.
        rr�rWr�r�)r�r�r�r7r�Nr�r�r�)r�UNSUBSCRIBE_MESSAGE_TYPESr��remover�r8r�r��PUBLISH_MESSAGE_TYPESr@r�)r6r*r�Zmessage_typer�r�r��handlerr$r$r%r�-sH



zPubSub.handle_messagecCsrx*t|j�D]\}}|dkrtd|��qWx*t|j�D]\}}|dkr8td|��q8Wt|||d�}|j�|S)Nz'Channel: '%s' has no handler registeredz'Pattern: '%s' has no handler registered)�daemon)rr�rr��PubSubWorkerThreadr�)r6�
sleep_timer�r�r�r�Zthreadr$r$r%�
run_in_threadhszPubSub.run_in_thread)r�r�)r�r�)NF)Tr)Fr)N)F)rF)rCrDrErFr�r�r�r:rIrNrOrkrJr��propertyr�rWr�rSr�r�r�r�r�r�r�r�r�r�r�r$r$r$r%rD0
s6
	






;rDcs.eZdZd�fdd�	Zdd�Zdd�Z�ZS)	r�Fcs.tt|�j�||_||_||_tj�|_dS)N)	r;r�r:r�rEr��	threadingZEvent�_running)r6rEr�r�)r=r$r%r:xs
zPubSubWorkerThread.__init__cCsN|jj�rdS|jj�|j}|j}x|jj�r@|jd|d�q&W|j�dS)NT)r�r@)r�Zis_setr�rEr�r�rJ)r6rEr�r$r$r%�runs

zPubSubWorkerThread.runcCs|jj�dS)N)r�r�)r6r$r$r%�stop�szPubSubWorkerThread.stop)F)rCrDrEr:r�r�rGr$r$)r=r%r�wsr�c@s�eZdZdZdddhZdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd1d*d+�Zd,d-�Zd.d/�Zd0S)2r2a_
    Pipelines provide a way to transmit multiple commands to the Redis server
    in one transmission.  This is convenient for batch processing, such as
    saving all the values in a list to Redis.

    All commands executed within a pipeline are wrapped with MULTI and EXEC
    calls. This guarantees all commands executed in the pipeline will be
    executed atomically.

    Any command raising an exception does *not* halt the execution of
    subsequent commands in the pipeline. Instead, the exception is caught
    and its instance is placed into the response list returned by execute().
    Code iterating over the response list should be able to deal with an
    instance of an exception as a potential value. In general, these will be
    ResponseError exceptions, such as those raised when issuing a command
    on a key of a different datatype.
    ZDISCARD�EXEC�UNWATCHcCs0||_d|_||_||_||_d|_|j�dS)NF)rr(r+r3r4�watchingrk)r6rr+r3r4r$r$r%r:�szPipeline.__init__cCs|S)Nr$)r6r$r$r%rI�szPipeline.__enter__cCs|j�dS)N)rk)r6rKrLrMr$r$r%rN�szPipeline.__exit__cCs&y|j�Wntk
r YnXdS)N)rkr�)r6r$r$r%rO�szPipeline.__del__cCs
t|j�S)N)r�
command_stack)r6r$r$r%�__len__�szPipeline.__len__cCsdS)z@Pipeline instances should  always evaluate to True on Python 2.7Tr$)r6r$r$r%�__nonzero__�szPipeline.__nonzero__cCsdS)z?Pipeline instances should  always evaluate to True on Python 3+Tr$)r6r$r$r%�__bool__�szPipeline.__bool__cCs~g|_t�|_|jrT|jrTy|jjd�|jj�Wntk
rR|jj�YnXd|_d|_	|jrz|j
j|j�d|_dS)Nr�F)r�r��scriptsr�r(rRrXrrT�explicit_transactionrrP)r6r$r$r%rk�szPipeline.resetcCs&|jrtd��|jrtd��d|_dS)z�
        Start a transactional block of the pipeline after WATCH commands
        are issued. End the transactional block with `execute`.
        z"Cannot issue nested calls to MULTIz:Commands without an initial WATCH have already been issuedTN)r�rr�)r6r$r$r%�multi�s
zPipeline.multicOs2|js|ddkr&|jr&|j||�S|j||�S)Nr�WATCH)r�r��immediate_execute_command�pipeline_execute_command)r6r#rkr$r$r%rW�szPipeline.execute_commandcOs�|d}|j}|s(|jj||j�}||_y|j|�|j||f|�Sttfk
r�}z||j�|j	rv|j
�td��|jo�t
|t�s�|j
��y|j|�|j||f|�Sttfk
r�|j
��YnXWYdd}~XnXdS)z�
        Execute a command immediately, but don't auto-retry on a
        ConnectionError if we're already WATCHing a variable. Used when
        issuing WATCH or subsequent commands retrieving their values but before
        MULTI is called.
        rz=A ConnectionError occurred on while watching one or more keysN)r(rr)r4rRrSrrrTr�rkrrr)r6r#r�rUrQrVr$r$r%r��s.

z"Pipeline.immediate_execute_commandcOs|jj||f�|S)ar
        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 all commands queued in the pipe.
        )r�rc)r6r#r�r$r$r%r�sz!Pipeline.pipeline_execute_commandc Cs tdifg|difg�}|jdd�|D��}|j|�g}y|j|d�Wn0tk
rz}z|jd|f�WYdd}~XnXx�t|�D]�\}}	t|	dkr�|j||	dtf�q�y|j|d�Wq�tk
�r
}z*|j||d|	d�|j||f�WYdd}~Xq�Xq�Wy|j|d�}
Wn*t	k
�rJ|�rD|dd��YnXd|_
|
dk�rdtd	��x|D]\}}|
j||��qjWt
|
�t
|�k�r�|jj�td
��|�r�|j||
�g}x\t|
|�D]N\}}
t|t��s|
\}}|d}||jk�r|j||f|�}|j|��q�W|S)
N�MULTIr�cSsg|]\}}t|kr|�qSr$)r)rIr#r�r$r$r%r�,sz1Pipeline._execute_transaction.<locals>.<listcomp>r$rrWFzWatched variable changed.z6Wrong number of response items from pipeline execution)r�)r�)r�
pack_commands�send_packed_commandrSrrcrhr�annotate_exceptionrr�r�insertrr(rT�raise_first_errorr	rr�r+)r6r(r��raise_on_errorZcmds�all_cmdsr-rVr�r�r*r7r�rmr#r�rUr$r$r%�_execute_transaction*sR
 $

zPipeline._execute_transactionc	Cs�|jdd�|D��}|j|�g}x\|D]T\}}y|j|j||df|��Wq(tk
rz}z|j|�WYdd}~Xq(Xq(W|r�|j||�|S)NcSsg|]\}}|�qSr$r$)rIr#r$r$r$r%r�msz.Pipeline._execute_pipeline.<locals>.<listcomp>r)r�r�rcrSrr�)	r6r(r�r�r�r*r#r�rVr$r$r%�_execute_pipelineks
 zPipeline._execute_pipelinecCsBx<t|�D]0\}}t|t�r
|j||d||d�|�q
WdS)NrWr)rhrrr�)r6r�r*r�r�r$r$r%r�|s
zPipeline.raise_first_errorcCsBdjtt|��}d||t|jd�f}|f|jdd�|_dS)Nr�z.Command # %d (%s) of pipeline caused error: %srrW)r�rrr#)r6Z	exceptionr/r�rm�msgr$r$r%r��szPipeline.annotate_exceptioncKs6tj|||f|�}||jkr$d|_n|dkr2d|_|S)NFr�T)r�rS�UNWATCH_COMMANDSr�)r6r(rUr�r�r$r$r%rS�s
zPipeline.parse_responsecCs`t|j�}|j}dd�|D�}|d|��}t|�s\x(t||�D]\}}|s>|d|j�|_q>WdS)NcSsg|]
}|j�qSr$)r�)rI�sr$r$r%r��sz)Pipeline.load_scripts.<locals>.<listcomp>�
SCRIPT EXISTSzSCRIPT LOAD)r)rr�r��allr	r�r�)r6r�Z	immediateZshasr�r�Zexistr$r$r%�load_scripts�s
zPipeline.load_scriptsTcCs�|j}|r|jrgS|jr&|j�|js2|jr:|j}n|j}|j}|s`|j	j
d|j�}||_zfy||||�Stt
fk
r�}z4|j�|jr�td��|jo�t|t
�s��||||�Sd}~XnXWd|j�XdS)z0Execute all the commands in the current pipeliner�z=A ConnectionError occurred on while watching one or more keysN)r�r�r�rr3r�r�r�r(rr)r4rrrTrrrrk)r6r��stackr:rQrVr$r$r%r:�s.zPipeline.executecGs|jrtd��|jd|��S)z$Watches the values at keys ``names``z"Cannot issue a WATCH after a MULTIr�)r�)r�rrW)r6r�r$r$r%r9�szPipeline.watchcCs|jr|jd�pdS)z'Unwatches all previously specified keysr�T)r�rW)r6r$r$r%r��szPipeline.unwatchN)T)rCrDrErFr�r:rIrNrOr�r�r�rkr�rWr�r�r�r�r�r�rSrr:r9r�r$r$r$r%r2�s.
*A	
'r2c@s(eZdZdZdd�Zggdfdd�ZdS)r�z?An executable Lua script object returned by ``register_script``cCs>||_||_t|t�r*|jj�}|j|�}tj|�j	�|_
dS)N)�registered_clientr�rrrrgri�hashlibZsha1Z	hexdigestr�)r6rr�rlr$r$r%r:�s


zScript.__init__NcCs�|dkr|j}t|�t|�}t|t�r4|jj|�y|j|jt|�f|��St	k
r�|j
|j�|_|j|jt|�f|��SXdS)z1Execute the script, passing any required ``args``N)rr�rr2r��addr�r�rrr�r�)r6r"r#rHr$r$r%�__call__�s
zScript.__call__)rCrDrErFr:rr$r$r$r%r��sr�c@sXeZdZdZddd�Zdd�Zdd�Zdd	d
�Zdd�Zd
d�Z	e
dd��Zdd�ZdS)r�z0
    Command builder for BITFIELD commands.
    NcCs||_||_||_|j�dS)N)rHrf�_default_overflowrk)r6rHrfr�r$r$r%r:�szBitFieldOperation.__init__cCs"g|_d|_|j|jp|j�dS)zL
        Reset the state of the instance to when it was constructed
        ZWRAPN)�
operations�_last_overflow�overflowr)r6r$r$r%rk�szBitFieldOperation.resetcCs,|j�}||jkr(||_|jjd|f�|S)a
        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.
        ZOVERFLOW)r5r
r	rc)r6rr$r$r%rs

zBitFieldOperation.overflowcCs*|dk	r|j|�|jjd|||f�|S)a�
        Increment a bitfield by a given amount.
        :param fmt: format-string for the bitfield being updated, 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 increment: value to increment the bitfield by.
        :param str overflow: overflow algorithm. Defaults to WRAP, but other
            acceptable values are SAT and FAIL. See the Redis docs for
            descriptions of these algorithms.
        :returns: a :py:class:`BitFieldOperation` instance.
        Nr�)rr	rc)r6�fmtr�Z	incrementrr$r$r%r�s
zBitFieldOperation.incrbycCs|jjd||f�|S)a�
        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:`BitFieldOperation` instance.
        r�)r	rc)r6rr�r$r$r%r@%s
zBitFieldOperation.getcCs|jjd|||f�|S)a�
        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: value to set at the given position.
        :returns: a :py:class:`BitFieldOperation` instance.
        r)r	rc)r6rr�rZr$r$r%r�2szBitFieldOperation.setcCs(d|jg}x|jD]}|j|�qW|S)NZBITFIELD)rfr	r!)r6rmZopsr$r$r%r�@s
zBitFieldOperation.commandcCs|j}|j�|jj|�S)a#
        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.
        )r�rkrHrW)r6r�r$r$r%r:GszBitFieldOperation.execute)N)N)
rCrDrErFr:rkrr�r@r�r�r�r:r$r$r$r%r��s


r�)FF)aZ
__future__r�	itertoolsrr)r%r;r�r�r�rZ
redis._compatrrrrrr	r
rrZredis.connectionr
rrZ
redis.lockrZredis.exceptionsrrrrrrrrrZ	SYM_EMPTYrr&r+r0r3r,r4rOrSrgrlr'r�r�r�r�r�r�r�rjr�r�r�rQr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�ZStrictRedisrFrDZThreadr�r2r�r�r$r$r$r%�<module>s�,,&

|?IA"