HEX
Server: LiteSpeed
System: Linux kapuas.iixcp.rumahweb.net 5.14.0-427.42.1.el9_4.x86_64 #1 SMP PREEMPT_DYNAMIC Fri Nov 1 14:58:02 EDT 2024 x86_64
User: mirz4654 (1666)
PHP: 8.1.33
Disabled: system,exec,escapeshellarg,escapeshellcmd,passthru,proc_close,proc_get_status,proc_nice,proc_open,proc_terminate,shell_exec,popen,pclose,dl,pfsockopen,leak,apache_child_terminate,posix_kill,posix_mkfifo,posix_setsid,posix_setuid,posix_setpgid,ini_alter,show_source,define_syslog_variables,symlink,syslog,openlog,openlog,closelog,ocinumcols,listen,chgrp,apache_note,apache_setenv,debugger_on,debugger_off,ftp_exec,dll,ftp,myshellexec,socket_bind,mail,posix_getwpuid
Upload Files
File: //lib/python3.9/site-packages/redis/__pycache__/client.cpython-39.pyc
a

��b*�@s�ddlZddlZddlZddlZddlZddlZddlmZddlm	Z	m
Z
mZmZddl
mZmZmZddlmZmZmZmZmZmZmZmZddlmZddlmZmZdZd	Z d
Z!dd�Z"d
d�Z#Gdd�de$�Z%dd�Z&dd�Z'dd�Z(dd�Z)e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*e*d�Z+dd�Z,dd�Z-dd�Z.d d!�Z/d"d#�Z0d}d%d&�Z1d'd(�Z2d)d*�Z3d+d,�Z4d-d.�Z5d/d0�Z6d1d2�Z7d3d4�Z8d5d6�Z9d7d8�Z:d9d:�Z;d;d<�Z<d=d>�Z=d?d@�Z>dAdB�Z?dCdD�Z@dEdF�ZAdGdH�ZBdIdJ�ZCdKdL�ZDdMdN�ZEdOdP�ZFdQdR�ZGdSdT�ZHdUdV�ZIdWdX�ZJdYdZ�ZKd[d\�ZLd]d^�ZMd_d`�ZNdadb�ZOdcdd�ZPdedf�ZQdgdh�ZRdidj�ZSdkdl�ZTdmdn�ZUdodp�ZVGdqdr�dr�ZWGdsdt�dteWe
e	e�ZXeXZYGdudv�dv�ZZGdwdx�dx�Z[Gdydz�dzej\�Z]Gd{d|�d|eX�Z^dS)~�N)�chain)�CoreCommands�RedisModuleCommands�SentinelCommands�list_or_args)�ConnectionPool�
SSLConnection�UnixDomainSocketConnection)�ConnectionError�ExecAbortError�ModuleError�PubSubError�
RedisError�
ResponseError�TimeoutError�
WatchError��Lock)�safe_str�str_if_bytes��EMPTY_RESPONSE�NEVER_DECODEcCs6|sdSzt|�}Wnty(YdS0tj�|�S)z5Converts a unix timestamp to a Python datetime objectN)�int�
ValueError�datetimeZ
fromtimestamp��response�r�0/usr/lib/python3.9/site-packages/redis/client.py�timestamp_to_datetime$sr cCst�|��|�S�N)�dict�fromkeys�split)Z
key_string�callbackrrr�string_keys_to_dict/sr&csfeZdZdZdd�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"|��D]\}}|||��<qdSr!)�items�upper)�self�data�k�vrrr�__init__6szCaseInsensitiveDict.__init__cst��|���Sr!)�super�__contains__r)�r*r,��	__class__rrr0:sz CaseInsensitiveDict.__contains__cst��|���dSr!)r/�__delitem__r)r1r2rrr4=szCaseInsensitiveDict.__delitem__cst��|���Sr!)r/�__getitem__r)r1r2rrr5@szCaseInsensitiveDict.__getitem__Ncst��|��|�Sr!)r/�getr))r*r,�defaultr2rrr6CszCaseInsensitiveDict.getcst��|��|�dSr!)r/�__setitem__r))r*r,r-r2rrr8FszCaseInsensitiveDict.__setitem__cst|�}t��|�dSr!)r'r/�update�r*r+r2rrr9IszCaseInsensitiveDict.update)N)�__name__�
__module__�__qualname__�__doc__r.r0r4r5r6r8r9�
__classcell__rrr2rr'3sr'cCsPt|�}d|}tdd�|��D��}d}|D]}||vr.t||�||<q.|S)zDParse the results of Redis's DEBUG OBJECT command into a Python dictztype:css|]}|�d�VqdS��:N�r$)�.0Zkvrrr�	<genexpr>Trz%parse_debug_object.<locals>.<genexpr>)�refcountZserializedlengthZlruZlru_seconds_idle)rr"r$r)rZ
int_fieldsZfieldrrr�parse_debug_objectNsrFcCs|dvrt|�S|S)z&Parse the results of an OBJECT command)ZidletimerE)�int_or_none)rZinfotyperrr�parse_object`srHcs�i}t|�}�fdd��|��D]�}|r |�d�s |�d�dkr�|�dd�\}}|dkrh|�dd�\}}|dkr�|�d	g���|��q��|�||<q |�d
g��|�q |S)z;Parse the result of Redis's INFO command into a Python dictcs�d|vsd|vrJz d|vr$t|�WSt|�WSWq~tyF|YS0n4i}|�d�D] }|�dd�\}}�|�||<qX|SdS)N�,�=�.�)�floatrrr$�rsplit)�valueZsub_dict�itemr,r-��	get_valuerrrRls
zparse_info.<locals>.get_value�#rA���rLZcmdstat_host�module�modulesZ__raw__)r�
splitlines�
startswith�findr$rN�
setdefault�append)r�info�line�keyrOrrQr�
parse_infogsr_cKs@t|ddd�}|��D]$\}}|�d�rt|ddd�||<q|S)z!Parse the results of MEMORY STATST)�decode_keys�decode_string_valueszdb.)�
pairs_to_dictr(rX)r�kwargsZstatsr^rOrrr�parse_memory_stats�s
�rd)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�portZquorumzrole-reported-timezs-down-timezslave-priorityzslave-repl-offsetzvoted-leader-epochcCs:t|t�}t|d�d��}dD]\}}||v||<q |S)N�flagsrI))Z	is_masterZmaster)Zis_slaveZslave)Zis_sdownZs_down)Zis_odownZo_down)Zis_sentinel�sentinel)Zis_disconnectedZdisconnected)Zis_master_downZmaster_down)�pairs_to_dict_typed�SENTINEL_STATE_TYPES�setr$)rP�resultrf�name�flagrrr�parse_sentinel_state�s

	rncCsttt|��Sr!�rn�maprrrrr�parse_sentinel_master�srqcCs,i}|D]}ttt|��}|||d<q|S)Nrlro)rrkrP�staterrr�parse_sentinel_masters�s
rscCsdd�|D�S)NcSsg|]}ttt|���qSrro�rCrPrrr�
<listcomp>�rz7parse_sentinel_slaves_and_sentinels.<locals>.<listcomp>rrrrr�#parse_sentinel_slaves_and_sentinels�srvcCs|r|dt|d�fpdS�NrrL�rrrrr�parse_sentinel_get_master�sryFcCst|duriS|s|rZ|ddd�}|r0tt|�}|ddd�}|rLtt|�}tt||��St|�}tt||��SdS)z-Create a dict given a list of key/value pairsN�rL)rprr"�zip�iter)rr`ra�keys�values�itrrrrb�s

rbc	CsXt|�}i}t||�D]<\}}||vrJz|||�}WntyHYn0|||<q|Sr!)r|r{�	Exception)rZ	type_inforrkr^rOrrrrh�s
rhcKs:|r|�d�s|S|�dt�}t|�}tt|t||���S)zr
    If ``withscores`` is specified in the options, return the response as
    a list of (value, score) pairs
    Z
withscores�score_cast_func)r6rMr|�listr{rp)r�optionsr�rrrr�zset_score_pairs�s
r�cs:�r|�d�s�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���qSr!r�rC�i��nrrrrurz&sort_return_tuples.<locals>.<listcomp>)r6r�r{�range�rr�rr�r�sort_return_tuplessr�cCs|durdSt|�Sr!rxrrrrrGsrGcCsL|durdSg}|D]2}|dur<|�|dt|d�f�q|�d�q|S)NrrL)NN)r[rb)rr+�rrrr�parse_stream_listsr�cCst|dd�S)NT�r`�rbrrrr�pairs_to_dict_with_str_keys(sr�cCsttt|��Sr!)r�rpr�rrrr�parse_list_of_dicts,sr�cKs|�dd�r|St|�S)N�parse_justidF�r6r�r�rrr�parse_xclaim0sr�cKs |�dd�r|dSt|d�S)Nr�FrLr�r�rrr�parse_xautoclaim6sr�cKs�t|dd�}|�dd�sj|d}|dur@|dt|d�f|d<|d}|dur�|dt|d�f|d<n,d	d
�|dD�|d<dd
�|dD�|d<|S)NTr�ZfullFzfirst-entryrrLz
last-entrycSsi|]\}}|t|��qSrr�)rCZ_id�entryrrr�
<dictcomp>Frz&parse_xinfo_stream.<locals>.<dictcomp>�entriescSsg|]}t|dd��qS)Tr�r�)rC�grouprrrruGsz&parse_xinfo_stream.<locals>.<listcomp>r�)rbr6)rr�r+�firstZlastrrr�parse_xinfo_stream<s�
r�cCs|durgSdd�|D�S)NcSs g|]}|dt|d�g�qS)rrL)r��rCr�rrrruPrzparse_xread.<locals>.<listcomp>rrrrr�parse_xreadMsr�cKsD|�dd�rt|�Sdd�|dp$gD�}|d|d|d|d	�S)
NZparse_detailFcSsg|]\}}|t|�d��qS))rl�pendingrx)rCr��prrrruVrz"parse_xpending.<locals>.<listcomp>�rrLrz)r��min�max�	consumers)r6�parse_xpending_range)rr�r�rrr�parse_xpendingSs�r�csd��fdd�|D�S)N)Z
message_idZconsumerZtime_since_deliveredZtimes_deliveredcsg|]}tt�|���qSr)r"r{r��r,rrruarz(parse_xpending_range.<locals>.<listcomp>rrrr�rr�_sr�cCs|durdSt|�Sr!�rMrrrr�
float_or_nonedsr�cCst|�dkS�N�OK�rrrrr�bool_okjsr�cKs&|durdS|�d�rt|�St|�S)NZas_score)r6rMrr�rrr�
parse_zaddns

r�cKs8g}t|���D]"}|�tdd�|�d�D���q|S)Ncss|]}|�dd�VqdS)rJrLNrB)rCZpairrrrrDzrz$parse_client_list.<locals>.<genexpr>� )rrWr[r"r$)rr�Zclients�crrr�parse_client_listvs r�cKsdd�|D�}|rt|�piS)NcSs g|]}|durt|�nd�qSr!r�r�rrrrurz$parse_config_get.<locals>.<listcomp>r�r�rrr�parse_config_get~sr�cKs|\}}t|�|fSr!rx�rr��cursorr�rrr�
parse_scan�sr�cKs |\}}t|�|rt|�pifSr!)rrbr�rrr�parse_hscan�sr�cKs8|�dt�}|\}}t|�}t|�tt|t||���fS)Nr�)r6rMr|rr�r{rp)rr�r�r�r�rrrr�parse_zscan�sr�cKsdd�|D�S)NcSs g|]}|durt|�nd�qSr!r�)rCZscorerrrru�rz!parse_zmscore.<locals>.<listcomp>rr�rrr�
parse_zmscore�sr�cs2|�dd�rdnd��fdd���fdd�|D�S)	N�decode_responsesFr�� csd|dt|d�t|d�d�}t|dt�rB��|d�|d<n|d|d<��|d�|d<|S)	NrrLrz)�id�
start_timeZdurationr��commandZ
complexity�)r�
isinstancer��join)rPrk)�spacerr�
parse_item�s z%parse_slowlog_get.<locals>.parse_itemcsg|]}�|��qSrrrt)r�rrru�rz%parse_slowlog_get.<locals>.<listcomp>)r6r�r)r�r�r�parse_slowlog_get�sr�cKs~|�dd�rt|�S|�dd�rv|�dd�r@dd�|dD�}ndd�|dD�}t|d	�|t|d
�t|d�iSt|�S)a
    Parse the response from `STRALGO` command.
    Without modifiers the returned value is string.
    When LEN is given the command returns the length of the result
    (i.e integer).
    When IDX is given the command returns a dictionary with the LCS
    length and all the ranges in both the strings, start and end
    offset for each string, where there are matches.
    When WITHMATCHLEN is given, each array representing a match will
    also have the length of the match at the beginning of the array.
    �lenF�idxZwithmatchlenc	Ss0g|](}t|d�gttt|dd����qS)rTN)rr�rp�tuple�rC�matchrrrru�s�z!parse_stralgo.<locals>.<listcomp>rLcSsg|]}ttt|���qSr)r�rpr�r�rrrru�rrrzr�)r6rr)rr��matchesrrr�
parse_stralgo�s��r�cKst|�}tdd�|��D��S)Ncss|]}|r|�d�VqdSr@rB)rCr]rrrrD�rz%parse_cluster_info.<locals>.<genexpr>)rr"rWr�rrr�parse_cluster_info�sr�c

Cs�|�d�}|�d�dd�\}}}}}}}}	|�d�d}||||||gg|	dkrVdndd�	}
t|�d	kr�t|dd��\}}|||
d
<|
d<||
fS)Nr���@r�	connectedTF)	�node_idrf�	master_idZlast_ping_sentZlast_pong_rcvd�epoch�slots�
migrationsr��	r�r�)r$r��_parse_slots)
r]Z
line_itemsr�Zaddrrfr��ping�pongr�r�Z	node_dictr�r�rrr�_parse_node_line�s"
"�r�cCs�gg}}|D]�}d|vrF|dd��dd�\}}|�||dd��qd|vrz|dd��dd�\}}|�||dd��qdd	�|�d
�D�}|�|�q||fS)Nz->-rLrTZ	migrating)Zslotr�rrz-<-Z	importingcSsg|]}|�qSrr)rC�slrrrru�rz _parse_slots.<locals>.<listcomp>�-)r$r[)Zslot_rangesr�r�Zs_rangeZslot_idZdst_node_idZsrc_node_idrrrr��s

�
�r�cKs(t|ttf�r|��}tdd�|D��S)z�
    @see: https://redis.io/commands/cluster-nodes  # string / bytes
    @see: https://redis.io/commands/cluster-replicas # list of string / bytes
    css|]}tt|��VqdSr!)r�r)rCZnoderrrrD�rz&parse_cluster_nodes.<locals>.<genexpr>)r��str�bytesrWr"r�rrr�parse_cluster_nodes�sr�cs��ds�dr|St|�tkr(|g}n|}�dsH�dsH�dsH|Stdd�td��d	d�g����fd
d�dD�7��fd
d�|D�S)z�
    Parse the response of 'GEOSEARCH', GEORADIUS' and 'GEORADIUSBYMEMBER'
    commands according to 'withdist', 'withhash' and 'withcoord' labels.
    �storeZ
store_dist�withdist�	withcoord�withhashcSst|d�t|d�fSrwr��Zllrrr�<lambda>rz)parse_geosearch_generic.<locals>.<lambda>)r�r�r�cSs|Sr!r��xrrrr�rcsg|]}�|r�|�qSrr)rC�o)�castr�rrrurz+parse_geosearch_generic.<locals>.<listcomp>)r�r�r�cs$g|]}ttdd�t�|����qS)cSs|d|d�Srwr)Zfvrrrr�rz4parse_geosearch_generic.<locals>.<listcomp>.<lambda>)r�rpr{r�)�frrrur)�typer�rMr)rr�Z
response_listr)r�r�r�r�parse_geosearch_generics�
r�cKs�i}|D]�}i}t|d�}||d<t|d�|d<dd�|dD�|d<|d	|d
<|d|d<|d
|d<t|�dkr�|d|d<|d|d<|d|d<|||<q|S)NrrlrLZaritycSsg|]}t|��qSrr�)rCrmrrrru(rz!parse_command.<locals>.<listcomp>rzrfr�Z
first_key_posr�Zlast_key_pos�Z
step_count�Ztipsr�Zkey_specificationsr��subcommands)rrr�)rr��commandsr�Zcmd_dictZcmd_namerrr�
parse_command!s 
r�cKs"tt|ddd�|ddd���S)NrrzrL)r�r{r�rrr�parse_pubsub_numsub4sr�cKst|t�r|St|�dkSr��r�rrr�rrr�parse_client_kill8s
r�cKsx|durdSt|dd�}ttt|d��|d<ttt|d��|d<t|d�|d<t|dt�spt|dt�r�tt|d��d��|d<|ddgkr�g|d<d	|vr�t|d	t�s�t|d	t�r�tt|d	��d��|d	<|d	dgkr�g|d	<d
|v�rdd�|d
D�|d
<gg}}|d�d�D]&}d
|v�rF|�|�n
|�|��q,||d<||d<d|dv|d<|S)NTr�rfZ	passwordsr�r}r���channelsZ	selectorscSsg|]}ttt|���qSr�r�rpr)rC�selectorrrrruQsz%parse_acl_getuser.<locals>.<listcomp>r��
categoriesZonZenabled)	rbr�rprr�r�r�r$r[)rr�r+r�r�r�rrr�parse_acl_getuser>s8
�


r�cKsp|durdSt|t�rdg}|D]B}t|dd�}|�dd�}t|�|d<t|d�|d<|�|�qnt|�}|S)NTzclient-infor�zage-seconds)r�r�rbr6�parse_client_inforMr[r�)rr�r+�logZlog_data�client_inforrr�
parse_acl_logcs
r�cCsPi}t|��d�}|D]}|�d�\}}|||<qdD]}t||�||<q6|S)zg
    Parsing client-info in ACL Log in following format.
    "key1=value1 key2=value2 key3=value3"
    r�rJ>Zomem�multizargv-memZollZageZqbufztot-memZoblr�z	qbuf-free�subZidle�dbZpsub)rr$r)rOr�Zinfosr\r^Zint_keyrrrr�us
r�cCst|t�r|�dS�NT)r�rrrrr�parse_module_result�s
rcKs|�d�r|S|ot|�dkS)z�
    Handle SET result since GET argument is available since Redis 6.2.
    Parsing SET result into:
    - BOOL
    - String when GET argument is used
    r6r�)r6rr�rrr�parse_set_result�s
rcp@s�eZdZiede��ede��ede��eddd���ede��ede��ed	e	��ed
dd���edd
d���ede
��eddd���ede��ede��ede
��eddd���dd�eeedd�dd�e	ee	e	dd�eeeeeee	dd�e	edd�e	e	dd�dd�e	e	e	e	dd�edd�e	eee	e	e	e	e	eeed d�ee	e	ee	e	e	d!d�d"d�eeed#d�eeee	eeeed$d�ed%d�e	e e!d&d�ee"d'd�e	e	ee	e	e	e#e$e%e	e	e	e&e	e&e'e(ee	e"d(d�e)e*e	eee	e+e+e,e-e.e/e0d)�n�Z1d*S)+�
AbstractRediszyAUTH COPY EXPIRE EXPIREAT PEXPIRE PEXPIREAT 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|t�r|pt|�dkSr�r��r�rrrr��rzAbstractRedis.<lambda>ZSORTzZSCORE ZINCRBY GEODISTz|FLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE ASKING READONLY READWRITE RENAME SAVE SELECT SHUTDOWN SLAVEOF SWAPDB WATCH UNWATCH zBLPOP BRPOPcCs|rt|�pdSr!)r�rrrrr��rzSDIFF SINTER SMEMBERS SUNIONcCs|rt|�pt�Sr!)rjrrrrr��rzSZPOPMAX ZPOPMIN ZINTER ZDIFF ZUNION ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCOREzBZPOPMIN BZPOPMAXcCs"|r|d|dt|d�fp dS)NrrLrzr�rrrrr��rzZRANK ZREVRANKzXREVRANGE XRANGEzXREAD XREADGROUPzBGREWRITEAOF BGSAVEcCsdSrrrrrrr��rcCsttt|��Sr!r�rrrrr��rcCsttt|��Sr!r�rrrrr��rcCsttt|��Sr!r�rrrrr��rcCsttt|��Sr!r�rrrrr��rcCs|rt|�dkpdS)NrLFrxrrrrr��rcCsttt|��Sr!r�rrrrr��rcCst|�Sr!rxr�rrrr��rcCst|�Sr!rxr�rrrr��rcCsttt|��Sr!r�rrrrr��rcCst|�Sr!rxr�rrrr��rcCsttt|��Sr!r�rrrrr�rcCsttt|��Sr!r�rrrrr�
rcCsttdd�|��S)NcSs$|dur t|d�t|d�fSdSrwr�r�rrrr�rz(AbstractRedis.<lambda>.<locals>.<lambda>)r�rprrrrr�s�cCs|rt|�piSr!r�rrrrr�rcCsdd�|D�S)NcSsg|]}t|��qSrr�)rC�mrrrrurz*AbstractRedis.<lambda>.<locals>.<listcomp>rrrrrr�rcCst|�dkS)NZPONGr�rrrrr�rcCs|r|p
dSr!rrrrrr� rcCsttt|��Sr!)r�rp�boolrrrrr�#rcCst|d�t|d�fSrwrxr�rrrr�8r)nzACL CATzACL DELUSERzACL GENPASSzACL GETUSERzACL HELPzACL LISTzACL LOADzACL LOGzACL SAVEzACL SETUSERz	ACL USERSz
ACL WHOAMIzCLIENT GETNAMEz	CLIENT IDzCLIENT KILLzCLIENT LISTzCLIENT INFOzCLIENT SETNAMEzCLIENT UNBLOCKzCLIENT PAUSEzCLIENT GETREDIRzCLIENT TRACKINGINFOzCLUSTER ADDSLOTSzCLUSTER ADDSLOTSRANGEzCLUSTER COUNT-FAILURE-REPORTSzCLUSTER COUNTKEYSINSLOTzCLUSTER DELSLOTSzCLUSTER DELSLOTSRANGEzCLUSTER FAILOVERzCLUSTER FORGETzCLUSTER GETKEYSINSLOTzCLUSTER INFOzCLUSTER KEYSLOTzCLUSTER MEETz
CLUSTER NODESzCLUSTER REPLICASzCLUSTER REPLICATEz
CLUSTER RESETzCLUSTER SAVECONFIGzCLUSTER SET-CONFIG-EPOCHzCLUSTER SETSLOTzCLUSTER SLAVESZCOMMANDz
COMMAND COUNTzCOMMAND GETKEYSz
CONFIG GETzCONFIG RESETSTATz
CONFIG SETzDEBUG OBJECTzFUNCTION DELETEzFUNCTION FLUSHzFUNCTION RESTOREZGEOHASHZGEOPOSZ	GEOSEARCHZ	GEORADIUSZGEORADIUSBYMEMBERZHGETALLZHSCAN�INFOZLASTSAVEzMEMORY PURGEzMEMORY STATSzMEMORY USAGEzMODULE LOADz
MODULE UNLOADzMODULE LISTZOBJECT�PINGZQUITZSTRALGOz
PUBSUB NUMSUBZ	RANDOMKEYZRESETZSCAN�
SCRIPT EXISTSzSCRIPT FLUSHzSCRIPT KILL�SCRIPT LOADzSENTINEL CKQUORUMzSENTINEL FAILOVERzSENTINEL FLUSHCONFIGz SENTINEL GET-MASTER-ADDR-BY-NAMEzSENTINEL MASTERzSENTINEL MASTERSzSENTINEL MONITORzSENTINEL RESETzSENTINEL REMOVEzSENTINEL SENTINELSzSENTINEL SETzSENTINEL SLAVESZSETzSLOWLOG GETzSLOWLOG LENz
SLOWLOG RESETZSSCANZTIMEZXCLAIMZ
XAUTOCLAIMz
XGROUP CREATEzXGROUP DELCONSUMERzXGROUP DESTROYzXGROUP SETIDzXINFO CONSUMERSzXINFO GROUPSzXINFO STREAMZXPENDINGZZADDZZSCANZZMSCOREN)2r;r<r=r&rrrMr�r�r�r�rGr�r�rr�r�r�r�r�r�r�r�r�rFr�r�r_r rdrrHr�r�r�ryrqrsrvrr�r�r�r�r�r�r�r�r��RESPONSE_CALLBACKSrrrrr�sD�������������� ��%��(�)�*�+�,��rc%@seZdZdZedd��Zdddddddddddd	ddd
d
gd
ddddddd
dd
d
dddd
dddddf%dd
�Zdd�Zdd�Zdd�Z	dd�Z
dd�Zd6dd�Zdd�Z
d7dd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�ZdS)8�Redisa�
    Implementation of the Redis protocol.

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

    Pipelines derive from this, implementing how
    the commands are sent and received to the Redis server. Based on
    configuration, an instance will either use a ConnectionPool, or
    Connection object to talk to redis.
    cKstj|fi|��}||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://` creates a TCP socket connection. See more at:
          <https://www.iana.org/assignments/uri-schemes/prov/redis>
        - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
          <https://www.iana.org/assignments/uri-schemes/prov/rediss>
        - ``unix://``: creates a Unix Domain Socket connection.

        The username, password, hostname, path and all querystring values
        are passed through urllib.parse.unquote in order to replace any
        percent-encoded values with their corresponding characters.

        There are several ways to specify a database number. The first value
        found will be used:

            1. A ``db`` querystring option, e.g. redis://localhost?db=0
            2. If using the redis:// or rediss:// schemes, the path argument
               of the url, e.g. redis://localhost/0
            3. A ``db`` keyword argument to this function.

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

        All querystring options are cast to their appropriate Python types.
        Boolean arguments can be specified with string values "True"/"False"
        or "Yes"/"No". Values that cannot be properly cast cause a
        ``ValueError`` to be raised. Once parsed, the querystring arguments
        and keyword arguments are passed to the ``ConnectionPool``'s
        class initializer. In the case of conflicting arguments, querystring
        arguments always win.

        )�connection_pool)r�from_url)�cls�urlrcr
rrrrVs*zRedis.from_urlZ	localhosti�rNzutf-8�strictF�requiredc&'Cs|	s�|
durt�td��|
}|dur8t�td��|}|durJ|�t�||#||||||t�|$�||!|"|%d�
}&|
dur�|&�|
td��n@|&�|||||d��|r�|&�t	||||||||||||d�
�t
fi|&��}	|	|_d|_| r�|j�
d	�|_t|jj�|_dS)
a4
        Initialize a new Redis client.
        To specify a retry policy for specific errors, first set
        `retry_on_error` to a list of the error/s to retry on, then set
        `retry` to a valid `Retry` object.
        To retry on TimeoutError, `retry_on_timeout` can also be set to `True`.
        Nz/"charset" is deprecated. Use "encoding" insteadz5"errors" is deprecated. Use "encoding_errors" insteadT)
r��username�password�socket_timeout�encoding�encoding_errorsr��retry_on_error�retry�max_connections�health_check_interval�client_name�redis_connect_func)�path�connection_class)�hostre�socket_connect_timeout�socket_keepalive�socket_keepalive_options)
r�ssl_keyfile�ssl_certfile�
ssl_cert_reqs�ssl_ca_certs�ssl_ca_data�ssl_check_hostname�ssl_password�ssl_ca_path�ssl_validate_ocsp_stapled�ssl_validate_ocsp�ssl_ocsp_context�ssl_ocsp_expected_cert�_)�warnings�warn�DeprecationWarningr[r�copy�deepcopyr9r	rrr
�
connection�get_connectionr'r3r�response_callbacks)'r*r rer�rrr!r"r#r
Zunix_socket_pathrr�charset�errorsr��retry_on_timeoutrZsslr$r%r&r'r+r(r)r*r-r,r.r/r�single_connection_clientrrrrrrcrrrr.�s�/����
�����
��zRedis.__init__cCst|�j�dt|j��d�S)N�<�>)r�r;�reprr
�r*rrr�__repr__szRedis.__repr__cCs
|j��S)z!Get the connection pool's encoder)r
�get_encoderr@rrrrBszRedis.get_encodercCs|jjS)z'Get the connection's key-word arguments)r
Zconnection_kwargsr@rrr�get_connection_kwargsszRedis.get_connection_kwargscCs||j|<dS)zSet a custom Response CallbackN)r8)r*r�r%rrr�set_response_callbackszRedis.set_response_callbackcCst|||�dS)a
        This function can be used to add externally defined redis modules,
        and their namespaces to the redis client.

        funcname - A string containing the name of the function to create
        func - The function, being added to this class.

        ex: Assume that one has a custom redis module named foomod that
        creates command named 'foo.dothing' and 'foo.anotherthing' in redis.
        To load function functions into this namespace:

        from redis import Redis
        from foomodule import F
        r = Redis()
        r.load_external_module("foo", F)
        r.foo().dothing('your', 'arguments')

        For a concrete example see the reimport of the redisjson module in
        tests/test_connection.py::test_loading_external_modules
        N)�setattr)r*�funcname�funcrrr�load_external_moduleszRedis.load_external_moduleTcCst|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.
        )�Pipeliner
r8)r*�transaction�
shard_hintrrr�pipeline&s�zRedis.pipelinec
	Os�|�dd�}|�dd�}|�dd�}|�d|��~}z:|rB|j|�||�}|��}	|rZ|n|	WWd�Sty�|dur�|dkr�t�|�Yq2Yq20q2Wd�n1s�0YdS)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.
        rKN�value_from_callableF�watch_delayTr)�poprL�watch�executer�time�sleep)
r*rGZwatchesrcrKrMrN�pipeZ
func_valueZ
exec_valuerrrrJ2s

zRedis.transaction皙�����?c	Cs"|durt}||||||||d�S)aL
        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`` indicates whether calling ``acquire`` should block until
        the lock has been acquired or to fail immediately, causing ``acquire``
        to return False and the lock not being acquired. Defaults to True.
        Note this value can be overridden by passing a ``blocking``
        argument to ``acquire``.

        ``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. Note that as
        of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
        a Lua-based lock). So, it's unlikely you'll need this parameter, unless
        you have created your own custom lock class.

        ``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)�timeoutrS�blocking�blocking_timeout�thread_localr)r*rlrVrSrWrXZ
lock_classrYrrr�lockHs>�z
Redis.lockcKst|jfi|��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
)r*rcrrr�pubsub�szRedis.pubsubcCs
t|j�Sr!)�Monitorr
r@rrr�monitor�sz
Redis.monitorcCs|j|jdd�S)NT)r
r<)r3r
r@rrr�client�s�zRedis.clientcCs|Sr!rr@rrr�	__enter__�szRedis.__enter__cCs|��dSr!��close�r*�exc_type�	exc_value�	tracebackrrr�__exit__�szRedis.__exit__cCs|��dSr!rar@rrr�__del__�sz
Redis.__del__cCs.t|d�sdS|j}|r*d|_|j�|�dS)Nr6)�hasattrr6r
�release�r*�connrrrrb�s
zRedis.closecOs|j|�|j||fi|��S)z7
        Send a command and parse the response
        )�send_command�parse_response)r*rl�command_name�argsr�rrr�_send_command_parse_response�s
z"Redis._send_command_parse_responsecCs.|��|jdus&t|t|j��dur*|�dS)z�
        Close the connection and raise an exception
        if retry_on_error is not set or the error
        is not one of the specified error types
        NF)�
disconnectrr�r��r*rl�errorrrr�_disconnect_raise�s��zRedis._disconnect_raisec	sz�j}�d��jp$|j�fi����z<�j������fdd���fdd��W�js`|���Sn�jst|���0dS)z.Execute a command and return a parsed responsercs�j��g��Ri���Sr!�rqr�rprorlr�r*rrr��s���z'Redis.execute_command.<locals>.<lambda>cs���|�Sr!)ru�rt�rlr*rrr��rN)r
r6r7r�call_with_retryrj)r*rpr�Zpoolrrwr�execute_command�s�
��zRedis.execute_commandcKspz"t|vr|jdd�}n|��}Wn(tyJt|vrD|tYS�Yn0||jvrl|j||fi|��S|S)z'Parses a response from the Redis serverT)Zdisable_decoding)r�
read_responserrr8)r*r6ror�rrrrrn�s
zRedis.parse_response)TN)NrUTNNT)r;r<r=r>�classmethodrr.rArBrCrDrHrLrJrZr\r^r_r`rgrhrbrqrur{rnrrrrrIs�
.�
}
�
Jrc@sLeZdZdZe�d�Ze�d�Zdd�Zdd�Z	dd	�Z
d
d�Zdd
�ZdS)r]z�
    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||_|j�d�|_dS)N�MONITOR)r
r7r6)r*r
rrrr.�szMonitor.__init__cCs0|j�d�|j��}t|�s,td|����|S)Nr~zMONITOR failed: )r6rmr|r�r�r*rrrrr`�s

zMonitor.__enter__cGs|j��|j�|j�dSr!)r6rrr
rj)r*rprrrrgs
zMonitor.__exit__cCs�|j��}t|t�r&|jjj|dd�}|�dd�\}}|j�|�}|�	�\}}}d�
|j�|��}|�
dd�}|dkr�d}d}	d}
n4|�d	�r�d	}|d
d�}	d	}
n|�dd�\}}	d
}
t|�t|�||	|
|d�S)z)Parse the response from a monitor commandT��forcer�rLz\"�"Zluar�Zunixr�NrAZtcp)rRr��client_address�client_port�client_typer�)r6r|r�r��encoder�decoder$�
monitor_rer�r�r��
command_re�findall�replacerXrNrMr)r*rZcommand_timeZcommand_datarZdb_idr�r�r�r�r�rrr�next_command
s2


�zMonitor.next_commandccs|��VqdS)z)Listen for commands coming to the server.N)r�r@rrr�listen-szMonitor.listenN)
r;r<r=r>�re�compiler�r�r.r`rgr�r�rrrrr]�s

#r]c@s�eZdZdZdZdZdZd;dd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
edd��Zdd�Zdd�Zdd�Zdd�Zd<d!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd=d3d4�Zd>d5d6�Zd?d7d8�Zd@d9d:�Z dS)Ar[a*
    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.
    )�message�pmessage)�unsubscribe�punsubscribezredis-py-health-checkNFcCs|||_||_||_d|_t��|_||_|jdur>|j��|_|j�	|j
�|_|jjrdd|j
g|_
nd|jg|_
|��dS)Nr�spong)r
rK�ignore_subscribe_messagesr6�	threading�Event�subscribed_eventr�rB�encode�HEALTH_CHECK_MESSAGE�health_check_response_br��health_check_response�reset)r*r
rKr�r�rrrr.@s

zPubSub.__init__cCs|Sr!rr@rrrr`XszPubSub.__enter__cCs|��dSr!�r�rcrrrrg[szPubSub.__exit__cCs$z|��WntyYn0dSr!�r�r�r@rrrrh^szPubSub.__del__cCs^|jr.|j��|j��|j�|j�d|_i|_d|_t�|_i|_	t�|_
|j��dS)Nr)
r6rrZclear_connect_callbacksr
rjr��health_check_response_counterrj�pending_unsubscribe_channels�patterns�pending_unsubscribe_patternsr��clearr@rrrr�gs

zPubSub.resetcCs|��dSr!r�r@rrrrbtszPubSub.closecCs�|j��|j��|jrVi}|j��D]\}}|||jj|dd�<q(|jfi|��|jr�i}|j��D]\}}|||jj|dd�<qj|j	fi|��dS)zBRe-subscribe to any channels and patterns previously subscribed toTr�N)
r�r�r�r�r(r�r��	subscriber��
psubscribe)r*r6r�r,r-r�rrr�
on_connectws

zPubSub.on_connectcCs
|j��S)z@Indicates if there are subscriptions to any channels or patterns)r��is_setr@rrr�
subscribed�szPubSub.subscribedcGsj|jdur*|j�d|j�|_|j�|j�|j}d|ji}|jsJ|��|j||j	g|�Ri|��dS)z#Execute a publish/subscribe commandNr\�check_health)
r6r
r7rKZregister_connect_callbackr�r��clean_health_check_responses�_executerm)r*rpr6rcrrrr{�s
�zPubSub.execute_commandcCstd}|j}|jdkrp|dkrp|j||j|jd�rf|�||j�}|�|�rX|jd8_ntd�|���|d8}q
dS)zG
        If any health check responses are present, clean them
        �
r�rVrLz?A non health check response was cleaned by execute_command: {0}N)	r6r�r��can_readrr|�is_health_check_responser
�format)r*Zttlrlrrrrr��s
��z#PubSub.clean_health_check_responsescCs(|��|jrt|t�s|�|��dS)z�
        Close the connection and raise an exception
        if retry_on_timeout is not set or the error
        is not a TimeoutError. Otherwise, try to reconnect
        N)rrr;r�rZconnectrsrrr�_disconnect_raise_connect�sz PubSub._disconnect_raise_connectcs$�j����fdd���fdd��S)aU
        Connect manually upon disconnection. If the Redis server is down,
        this will fail and raise a ConnectionError as desired.
        After reconnection, the ``on_connect`` callback should have been
        called by the # connection to resubscribe us to any channels and
        patterns we were previously listening to
        cs��i���Sr!rr)rpr�rcrrr��rz!PubSub._execute.<locals>.<lambda>cs���|�Sr!)r�rxryrrr��r)rrz)r*rlr�rprcr)rpr�rlrcr*rr��s�zPubSub._executeTrcCsf|j}|durtd��|��|s8|j||j|d�s8dS|�||j�}|�|�rb|jd8_dS|S)z3Parse the response from a publish/subscribe commandN�Npubsub connection not set: did you forget to call subscribe() or psubscribe()?r�rL)r6�RuntimeErrorr�r�r�r|r�r�)r*�blockrVrlrrrrrn�s�
zPubSub.parse_responsecCs||j|jfvS)z�
        Check if the response is a health check response.
        If there are no subscriptions redis responds to PING command with a
        bulk response, instead of a multi-bulk with "pong" and the response.
        )r�r�rrrrr��s�zPubSub.is_health_check_responsecCsN|j}|durtd��|jrJt��|jkrJ|jd|jdd�|jd7_dS)Nr�rF)r�rL)r6r�rrRZnext_health_checkrmr�r�rkrrrr��s�zPubSub.check_healthcs(|jj�|jj���fdd�|��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|]\}}��|��|�qSrr)rCr,r-�r�r�rrr�rz*PubSub._normalize_keys.<locals>.<dictcomp>)r�r�r�r(r:rr�r�_normalize_keys�szPubSub._normalize_keyscOs�|rt|d|dd��}t�|�}|�|�|jdg|���R�}|�|�}|j�|�|jsp|j	�
�d|_|j�
|�|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()``.
        rrLNZ
PSUBSCRIBE)rr"r#r9r{r}r�r�r�r�rjr�r��difference_update)r*rprcZnew_patterns�ret_valrrrr�s



zPubSub.psubscribecGsP|r,t|d|dd��}|�t�|��}n|j}|j�|�|jdg|�R�S)zj
        Unsubscribe from the supplied patterns. If empty, unsubscribe from
        all patterns.
        rrLNZPUNSUBSCRIBE)rr�r"r#r�r�r9r{)r*rpr�rrrr�szPubSub.punsubscribecOs�|rt|d|dd��}t�|�}|�|�|jdg|���R�}|�|�}|j�|�|jsp|j	�
�d|_|j�
|�|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()``.
        rrLNZ	SUBSCRIBE)rr"r#r9r{r}r�r�r�r�rjr�r�r�)r*rprcZnew_channelsr�rrrr�)s



zPubSub.subscribecGsP|r,t|d|dd��}|�t�|��}n|j}|j�|�|jdg|�R�S)zi
        Unsubscribe from the supplied channels. If empty, unsubscribe from
        all channels
        rrLNZUNSUBSCRIBE)rr�r"r#r�r�r9r{)r*rpr�rrrr�CszPubSub.unsubscribeccs,|jr(|�|jdd��}|dur|VqdS)zBListen for messages on channels this client has been subscribed toT)r�N)r��handle_messagernrrrrr�Psz
PubSub.listencCs`|js>t��}|j�|�dur:t��|}td||�}ndS|jd|d�}|r\|�||�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.
        TgNF)r�rV)r�rRr��waitr�rnr�)r*r�rVr�Z
time_spentrrrr�get_messageWszPubSub.get_messagecCs|durdn|}|�d|�S)z'
        Ping the Redis server
        Nr�r�r{)r*r�rrrr�rszPubSub.pingcCs`|durdSt|d�}|dkr<||d|d|dd�}n2|dkrX|dd|dd�}n|d|d|dd�}||jvr�|d	kr�|d}||jvr�|j�|�|j�|d�n,|d}||jvr�|j�|�|j�|d�|js�|js�|j�	�||j
v�r@|dk�r|j�|d
d�}n|j�|dd�}|�r\||�dSn|dk�r\|�sX|j�r\dS|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.
        Nrr�rLrzr�)r��pattern�channelr+r�r�r�r�)
r�UNSUBSCRIBE_MESSAGE_TYPESr��remover�rOr�r�r�r��PUBLISH_MESSAGE_TYPESr6r�)r*rr�Zmessage_typer�r�r��handlerrrrr�ysV���





zPubSub.handle_messagecCst|j��D] \}}|dur
td|�d���q
|j��D] \}}|dur6td|�d���q6t||||d�}|��|S)Nz
Channel: 'z' has no handler registeredz
Pattern: ')�daemon�exception_handler)r�r(r
r��PubSubWorkerThread�start)r*�
sleep_timer�r�r�r�r��threadrrr�
run_in_thread�s�zPubSub.run_in_thread)NFN)Tr)Fr)N)F)rFN)!r;r<r=r>r�r�r�r.r`rgrhr�rbr��propertyr�r{r�r�r�rnr�r�r�r�r�r�r�r�r�r�r�r�rrrrr[3sB�
	








Ar[cs.eZdZd	�fdd�	Zdd�Zdd�Z�ZS)
r�FNcs0t���||_||_||_||_t��|_dSr!)	r/r.r�r\r�r�r�r��_running)r*r\r�r�r�r2rrr.�s
zPubSubWorkerThread.__init__c
Cs�|j��rdS|j��|j}|j}|j��r�z|jd|d�Wq$ty~}z&|jdur\�|�|||�WYd}~q$d}~00q$|��dS)NT)r�rV)	r�r�rjr\r�r��
BaseExceptionr�rb)r*r\r��errr�run�s



&zPubSubWorkerThread.runcCs|j��dSr!)r�r�r@rrr�stop�szPubSubWorkerThread.stop)FN)r;r<r=r.r�r�r?rrr2rr��sr�c@s�eZdZdZhd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd3d*d+�Zd,d-�Zd.d/�Zd0d1�Zd2S)4rIa_
    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.
    >�EXEC�DISCARD�UNWATCHcCs0||_d|_||_||_||_d|_|��dS)NF)r
r6r8rJrK�watchingr�)r*r
r8rJrKrrrr.�szPipeline.__init__cCs|Sr!rr@rrrr`szPipeline.__enter__cCs|��dSr!r�rcrrrrg
szPipeline.__exit__cCs$z|��WntyYn0dSr!r�r@rrrrh
szPipeline.__del__cCs
t|j�Sr!)r��
command_stackr@rrr�__len__szPipeline.__len__cCsdS)z1Pipeline instances should always evaluate to TrueTrr@rrr�__bool__szPipeline.__bool__cCs|g|_t�|_|jrR|jrRz|j�d�|j��WntyP|j��Yn0d|_d|_	|jrx|j
�|j�d|_dS)Nr�F)r�rj�scriptsr�r6rmr|r
rr�explicit_transactionr
rjr@rrrr�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�r@rrrr�1s�zPipeline.multicOs8|js|ddkr(|js(|j|i|��S|j|i|��S)Nr�WATCH)r�r��immediate_execute_command�pipeline_execute_command)r*rprcrrrr{>szPipeline.execute_commandcCs<|��|jr|��td��|jr.t|t�s8|���dS)z�
        Close the connection, reset watching state and
        raise an exception if we were watching,
        retry_on_timeout is not set,
        or the error is not a TimeoutError
        �=A ConnectionError occurred on while watching one or more keysN)rrr�r�rr;r�rrsrrr�_disconnect_reset_raiseCs�z Pipeline._disconnect_reset_raisecsP�d��j��s(�j���j����_�j������fdd���fdd��S)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.
        rcs�j��g��Ri���Sr!rvrrwrrr�hs���z4Pipeline.immediate_execute_command.<locals>.<lambda>cs���|�Sr!)r�rxryrrr�kr)r6r
r7rKrrz�r*rpr�rrwrr�Ys�z"Pipeline.immediate_execute_commandcOs|j�||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�r[r�rrrr�nsz!Pipeline.pipeline_execute_commandcCstdifg|difg�}|�dd�|D��}|�|�g}z|�|d�Wn2ty|}z|�d|f�WYd}~n
d}~00t|�D]�\}}	t|	dvr�|�||	dtf�q�z|�|d�Wq�t�y}z0|�||d|	d�|�||f�WYd}~q�d}~00q�z|�|d�}
Wn(t	�yH|�rB|dd��Yn0d|_
|
du�rbtd	��|D]\}}|
�||��qft
|
�t
|�k�r�|j��td
��|�r�|�||
�g}t|
|�D]R\}}
t|t��s|
\}}|d}||jv�r|j||fi|��}|�|��q�|S)N)�MULTI)r�cSsg|]\}}t|vr|�qSr)r)rCrpr�rrrru�rz1Pipeline._execute_transaction.<locals>.<listcomp>r0rrLFzWatched variable changed.z6Wrong number of response items from pipeline execution)r�
pack_commands�send_packed_commandrnrr[�	enumerater�annotate_exceptionrr�r�insertr�r6rr�raise_first_errorr{r�r�r8)r*r6r��raise_on_errorZcmds�all_cmdsr:r�r�r�rr+r��cmdrpr�rorrr�_execute_transaction}sZ�
$&

�zPipeline._execute_transactionc	Cs�|�dd�|D��}|�|�g}|D]Z\}}z"|�|j||dfi|���Wq&ty~}z|�|�WYd}~q&d}~00q&|r�|�||�|S)NcSsg|]\}}|�qSrr)rCrpr0rrrru�rz.Pipeline._execute_pipeline.<locals>.<listcomp>r)r�r�r[rnrr�)	r*r6r�r�r�rrpr�r�rrr�_execute_pipeline�s
""zPipeline._execute_pipelinecCs>t|�D]0\}}t|t�r|�||d||d�|�qdS)NrLr)r�r�rr�)r*r�rr�r�rrrr��s
zPipeline.raise_first_errorcCsFd�tt|��}d|�d|�d|jd��}|f|jdd�|_dS)Nr�z
Command # z (z) of pipeline caused error: rrL)r�rprrp)r*�	exceptionZnumberr�r��msgrrrr��s��zPipeline.annotate_exceptioncKs:tj|||fi|��}||jvr(d|_n|dkr6d|_|S)NFr�T)rrn�UNWATCH_COMMANDSr�)r*r6ror�rkrrrrn�s
zPipeline.parse_responsecCs`t|j�}|j}dd�|D�}|dg|�R�}t|�s\t||�D]\}}|s@|d|j�|_q@dS)NcSsg|]
}|j�qSr)�sha)rC�srrrru�rz)Pipeline.load_scripts.<locals>.<listcomp>r	r
)r�r�r��allr{Zscriptr�)r*r�Z	immediateZshas�existsr�Zexistrrr�load_scripts�s
zPipeline.load_scriptscCs4|��|jrtd��|jr&t|t�s0|���dS)z�
        Close the connection, raise an exception if we were watching,
        and raise an exception if retry_on_timeout is not set,
        or the error is not a TimeoutError
        r�N)rrr�rr;r�rr�rsrrr�_disconnect_raise_reset�s�z Pipeline._disconnect_raise_resetTcs��j��s�jsgS�jr"����js.�jr6�j�n�j��j��s\�j	�
d�j����_z0�j�
����fdd���fdd��W���S���0dS)z0Execute all the commands in the current pipeliner�cs�����Sr!rr)rlrQr��stackrrr�rz"Pipeline.execute.<locals>.<lambda>cs���|�Sr!)r�rxryrrr�rN)r�r�r�r�rJr�r�r�r6r
r7rKrrzr�)r*r�r)rlrQr�r*r�rrQs(
��zPipeline.executecCs|�d�dS)zg
        Flushes all previously queued commands
        See: https://redis.io/commands/DISCARD
        r�Nr�r@rrr�discard"szPipeline.discardcGs |jrtd��|jdg|�R�S)z$Watches the values at keys ``names``z"Cannot issue a WATCH after a MULTIr�)r�rr{)r*�namesrrrrP)szPipeline.watchcCs|jr|�d�pdS)z'Unwatches all previously specified keysr�T)r�r{r@rrr�unwatch/szPipeline.unwatchN)T)r;r<r=r>r�r.r`rgrhr�r�r�r�r{r�r�r�r�r�r�r�rnr�r�rQr�rPr�rrrrrI�s2

C

rI)FF)_r4rr�r�rRr1�	itertoolsrZredis.commandsrrrrZredis.connectionrrr	Zredis.exceptionsr
rrr
rrrrZ
redis.lockrZredis.utilsrrZ	SYM_EMPTYrrr r&r"r'rFrHr_rdrrirnrqrsrvryrbrhr�r�rGr�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�rrrrZStrictRedisr]r[�Threadr�rIrrrr�<module>s�(
,�

!% !'C