o
    ݭhw                 	   @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ d dlmZmZ d dl m!Z!m"Z"m#Z#m$Z$m%Z% d dl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5 ee6ejf Z7ee6ej8f Z9ee:e;f Z<ee6e;f Z=ee>e;e?f Z@e@ZAe@ZBe#ZCeeAeeA f ZDe@ZEe@ZFe@ZGee6e@f ZHe@ZIee6e:e@f ZJede>e;e?ZKed	e>e;e?ZLeEZMeee;e;f gdf ZNd
ZOdZPedeAdZQedeAe#ZRedddZSedeeEeTf dZUdeeQeeQ f deeeR  deeeQeRf  fddZVdd ZWdd ZXG dd deYZZdd Z[dd  Z\d!d" Z]d#d$ Z^i d%e6d&e6d'e6d(e6d)e6d*e6d+e6d,e6d-e6d.e6d/e6d0e6d1e6d2e6d3e6d4e6d5e6e6e6e6e6e6e6d6Z_d7d8 Z`d9d: Zad;d< Zbd=d> Zcd?d@ ZdddBdCZedDdE ZfdFdG ZgdHdI ZhdJdK ZidLdM ZjdNdO ZkdPdQ ZldRdS ZmdTdU ZndVdW ZodXdY ZpdZd[ Zqd\d] Zrd^d_ Zsd`da Ztdbdc Zuddde Zvdfdg Zwdhdi Zxdjdk Zydldm Zzdndo Z{dpdq Z|drds Z}dtdu Z~dvdw Zdxdy Zdzd{ Zd|d} Zd~d Zdd ZG dd deZG dd deZeeef ZedZG dd dZeZG dd deZG dd dZG dd dZG dd deZG dd deZeeef Zeeee;e>f df ee;e
f f Zee ZG dd deZG dd dZG dd dZdS )    N)AbstractSetAnyAsyncIterator	AwaitableCallableDictIterableListMappingMutableMappingNoReturnOptionalSequenceSetTupleTypeTypeVarUnion
ValuesViewcast)Protocol	TypedDict)
ConnectionConnectionPool
EncodableTSSLConnectionUnixDomainSocketConnection)
ConnectionError	DataErrorExecAbortErrorModuleErrorNoScriptErrorPubSubError
RedisErrorResponseErrorTimeoutError
WatchErrorLock)safe_strstr_if_bytesAnyKeyT	AnyFieldT    EMPTY_RESPONSE_KeyT)bound_ArgT_RedisTRedis_NormalizeKeysTkeysargsreturnc                 C   sj   zt |  ttt | } t| ttfr| g}nt| }W n ty+   tt	| g}Y nw |r3|
| |S N)iterr   r   r/   
isinstancebytesstrlist	TypeError
memoryviewextend)r5   r6   key_list rB   T/var/www/html/stock_analysis/be/venv/lib/python3.10/site-packages/aioredis/client.pylist_or_argsX   s   
rD   c                 C   s6   | sdS zt | } W n
 ty   Y dS w tj| S )z5Converts a unix timestamp to a Python datetime objectN)int
ValueErrordatetimefromtimestampresponserB   rB   rC   timestamp_to_datetimem   s   rK   c                 C   s   t |  |S r8   )dictfromkeyssplit)
key_stringcallbackrB   rB   rC   string_keys_to_dictx      rQ   c                       sf   e Zd ZdZdd Z fddZ fddZ fdd	Zd fdd	Z fddZ	 fddZ
  ZS )CaseInsensitiveDictz?Case insensitive dict implementation. Assumes string keys only.c                 C   s"   |  D ]
\}}|| | < qd S r8   )itemsupper)selfdatakvrB   rB   rC   __init__   s   zCaseInsensitiveDict.__init__c                       t  | S r8   )super__contains__rU   rV   rX   	__class__rB   rC   r]      rR   z CaseInsensitiveDict.__contains__c                    s   t  |  d S r8   )r\   __delitem__rU   r^   r_   rB   rC   ra      s   zCaseInsensitiveDict.__delitem__c                    r[   r8   )r\   __getitem__rU   r^   r_   rB   rC   rb      rR   zCaseInsensitiveDict.__getitem__Nc                    s   t  | |S r8   )r\   getrU   )rV   rX   defaultr_   rB   rC   rc      s   zCaseInsensitiveDict.getc                    s   t  | | d S r8   )r\   __setitem__rU   )rV   rX   rY   r_   rB   rC   re         zCaseInsensitiveDict.__setitem__c                    s   t |}t | d S r8   )rS   r\   updaterV   rW   r_   rB   rC   rg      s   zCaseInsensitiveDict.updater8   )__name__
__module____qualname____doc__rZ   r]   ra   rb   rc   re   rg   __classcell__rB   rB   r_   rC   rS   |   s    rS   c                 C   sP   t | } d|  } tdd |  D } d}|D ]}|| v r%t| | | |< q| S )zDParse the results of Redis's DEBUG OBJECT command into a Python dictztype:c                 s   s    | ]}| d V  qdS :NrN   ).0kvrB   rB   rC   	<genexpr>   s    z%parse_debug_object.<locals>.<genexpr>)refcountserializedlengthlrulru_seconds_idle)r*   rL   rN   rE   )rJ   
int_fieldsfieldrB   rB   rC   parse_debug_object   s   rz   c                 C   s   |dv rt | S | S )z&Parse the results of an OBJECT command)idletimert   )int_or_none)rJ   infotyperB   rB   rC   parse_object   s   r~   c                    s   i }t | }  fdd |  D ]D}|rT|dsT|ddkrK|dd\}}|dkr4|dd\}}|dkrD|d	g  | q |||< q|d
g | q|S )z;Parse the result of Redis's INFO command into a Python dictc                    sx   d| vsd| vr"zd| v rt | W S t| W S  ty!   |  Y S w i }| dD ]}|dd\}} |||< q)|S )N,=.   )floatrE   rF   rN   rsplit)valuesub_dictitemrX   rY   	get_valuerB   rC   r      s   

zparse_info.<locals>.get_value#ro   r   cmdstat_hostmodulemodules__raw__)r*   
splitlines
startswithfindrN   r   
setdefaultappend)rJ   infolinekeyr   rB   r   rC   
parse_info   s   r   c                 K   s@   t | ddd}| D ]\}}|drt |ddd||< q|S )z!Parse the results of MEMORY STATST)decode_keysdecode_string_valueszdb.)pairs_to_dictrT   r   )rJ   kwargsstatsr   r   rB   rB   rC   parse_memory_stats   s   

r   zcan-failover-its-masterzconfig-epochzdown-after-millisecondszfailover-timeoutzinfo-refreshzlast-hello-messagezlast-ok-ping-replyzlast-ping-replyzlast-ping-sentzmaster-link-down-timezmaster-portznum-other-sentinelsz
num-slaveszo-down-timezpending-commandszparallel-syncsport)quorumzrole-reported-timezs-down-timezslave-priorityzslave-repl-offsetzvoted-leader-epochc                 C   s:   t | t}t|d d}dD ]
\}}||v ||< q|S )Nflagsr   ))	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)pairs_to_dict_typedSENTINEL_STATE_TYPESsetrN   )r   resultr   nameflagrB   rB   rC   parse_sentinel_state  s
   
	r   c                 C      t tt| S r8   r   mapr*   rI   rB   rB   rC   parse_sentinel_master     r   c                 C   s,   i }| D ]}t tt|}|||d < q|S )Nr   r   )rJ   r   r   staterB   rB   rC   parse_sentinel_masters  s
   r   c                 C      dd | D S )Nc                 S   s   g | ]	}t tt|qS rB   r   rq   r   rB   rB   rC   
<listcomp>      z7parse_sentinel_slaves_and_sentinels.<locals>.<listcomp>rB   rI   rB   rB   rC   #parse_sentinel_slaves_and_sentinels  r   r   c                 C   s   | r| d t | d fpd S Nr   r   rE   rI   rB   rB   rC   parse_sentinel_get_master"     r   Fc                 C   sp   | du ri S |s
|r-| ddd }|rt t|}| ddd }|r&t t|}tt||S t| }tt||S )z-Create a dict given a list of key/value pairsN   r   )r   r*   rL   zipr9   )rJ   r   r   r5   valuesitrB   rB   rC   r   &  s   

r   c              	   C   sX   t | }i }t||D ]\}}||v r%z|| |}W n	 ty$   Y nw |||< q|S r8   )r9   r   	Exception)rJ   	type_infor   r   r   r   rB   rB   rC   r   9  s   
r   c                 K   s:   | r| ds	| S | dt}t| }tt|t||S )zr
    If ``withscores`` is specified in the options, return the response as
    a list of (value, score) pairs
    
withscoresscore_cast_func)rc   r   r9   r=   r   r   )rJ   optionsr   r   rB   rB   rC   zset_score_pairsH  s
   r   c                    s:   r| ds	S |d  tt fdd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']
    groupsc                 3   s    | ]
}|d   V  qd S r8   rB   rq   inrJ   rB   rC   rs   \      z%sort_return_tuples.<locals>.<genexpr>)rc   r=   r   rangerJ   r   rB   r   rC   sort_return_tuplesT  s    r   c                 C      | d u rd S t | S r8   r   rI   rB   rB   rC   r|   _     r|   c                 C   sL   | d u rd S g }| D ]}|d ur| |d t|d f q
| d q
|S )Nr   r   NN)r   r   )rJ   rW   rrB   rB   rC   parse_stream_liste  s   r   c                 C   s   t | ddS )NTr   r   rI   rB   rB   rC   pairs_to_dict_with_str_keysq     r   c                 C   r   r8   )r=   r   r   rI   rB   rB   rC   parse_list_of_dictsu  r   r   c                 K   s   | ddr| S t| S )Nparse_justidF)rc   r   r   rB   rB   rC   parse_xclaimy  s   r   c                 C   s`   t | dd}|d }|d ur|d t |d f|d< |d }|d ur.|d t |d f|d< |S )NTr   zfirst-entryr   r   z
last-entryr   )rJ   rW   firstlastrB   rB   rC   parse_xinfo_stream  s   r   c                 C   s   | d u rg S dd | D S )Nc                 S   s    g | ]}|d  t |d gqS r   r   )r   rq   r   rB   rB   rC   r          zparse_xread.<locals>.<listcomp>rB   rI   rB   rB   rC   parse_xread  s   r   c                 K   sD   | ddr
t| S dd | d pg D }| d | d | d |d	S )
Nparse_detailFc                 S   s   g | ]\}}|t |d qS ))r   pendingr   )rq   r   prB   rB   rC   r         z"parse_xpending.<locals>.<listcomp>   r   r   r   )r   minmax	consumers)rc   parse_xpending_range)rJ   r   r   rB   rB   rC   parse_xpending  s   r   c                    s   d  fdd| D S )N)
message_idconsumertime_since_deliveredtimes_deliveredc                    s   g | ]	}t t |qS rB   )rL   r   r   rX   rB   rC   r     r   z(parse_xpending_range.<locals>.<listcomp>rB   rI   rB   r   rC   r     s   r   c                 C   r   r8   r   rI   rB   rB   rC   float_or_none  r   r   c                 C      t | dkS NOKr*   rI   rB   rB   rC   bool_ok  r   r  c                 K   s&   | d u rd S | drt| S t| S )Nas_score)rc   r   rE   r   rB   rB   rC   
parse_zadd  s
   
r  c                 K   s8   g }t |  D ]}|tdd |dD  q|S )Nc                 s   s    | ]	}| d dV  qdS )r   r   Nrp   )rq   pairrB   rB   rC   rs     s    z$parse_client_list.<locals>.<genexpr> )r*   r   r   rL   rN   )rJ   r   clientscrB   rB   rC   parse_client_list  s    r	  c                 K   s   dd | D } | rt | pi S )Nc                 S   s    g | ]}|d urt |nd qS r8   r  r   rB   rB   rC   r     r   z$parse_config_get.<locals>.<listcomp>r   r   rB   rB   rC   parse_config_get  s   r
  c                 K   s   | \}}t ||fS r8   r   rJ   r   cursorr   rB   rB   rC   
parse_scan  s   r  c                 K   s    | \}}t ||rt|pi fS r8   )rE   r   r  rB   rB   rC   parse_hscan  s   r  c                 K   s8   | dt}| \}}t|}t|tt|t||fS )Nr   )rc   r   r9   rE   r=   r   r   )rJ   r   r   r  r   r   rB   rB   rC   parse_zscan  s   r  c                    s&   | ddrdnd  fdd| D S )Ndecode_responsesFr      c              	      sT   g | ]&}|d  t |d t |d t|d tr |d n |d dqS )r   r   r   r      )id
start_timedurationcommand)rE   r:   r=   joinr   spacerB   rC   r     s    

z%parse_slowlog_get.<locals>.<listcomp>)rc   r   rB   r  rC   parse_slowlog_get  s   
r  c                 K   s   t | } tdd |  D S )Nc                 s   s    | ]
}|r| d V  qdS rn   rp   rq   r   rB   rB   rC   rs     r   z%parse_cluster_info.<locals>.<genexpr>)r*   rL   r   r   rB   rB   rC   parse_cluster_info  s   r  c              	   C   sl   |  d}|  dd d \}}}}}}}}	dd |dd  D }
|||||||
|	dkr.dndd}||fS )	Nr     c                 S   s   g | ]}| d qS )-rp   )rq   slrB   rB   rC   r     s    z$_parse_node_line.<locals>.<listcomp>	connectedTF)node_idr   	master_idlast_ping_sentlast_pong_rcvdepochslotsr   rp   )r   
line_itemsr!  addrr   r"  pingpongr%  r   r&  	node_dictrB   rB   rC   _parse_node_line  s   
"
r,  c                 K   s   t |  }tdd |D S )Nc                 s   s    | ]}t |V  qd S r8   )r,  r  rB   rB   rC   rs     s    z&parse_cluster_nodes.<locals>.<genexpr>)r*   r   rL   )rJ   r   	raw_linesrB   rB   rC   parse_cluster_nodes  s   r.  c                    s   d sd r
| S t | tkr| g}n| }d s$d s$d s$|S tdd td d	d g fd
ddD 7 fdd|D S )Nstore
store_distwithdist	withcoordwithhashc                 S      t | d t | d fS r   r   llrB   rB   rC   <lambda>      z)parse_georadius_generic.<locals>.<lambda>)r1  r2  r3  c                 S   s   | S r8   rB   xrB   rB   rC   r7        c                    s   g | ]
}| r | qS rB   rB   )rq   o)r   r   rB   rC   r     s    z+parse_georadius_generic.<locals>.<listcomp>)r1  r3  r2  c                    s$   g | ]}t td d t |qS )c                 S   s   | d | d S r   rB   )fvrB   rB   rC   r7        z4parse_georadius_generic.<locals>.<listcomp>.<lambda>)r=   r   r   r   )frB   rC   r        $ )typer=   r   rE   )rJ   r   response_listrB   )r   r?  r   rC   parse_georadius_generic   s   
rC  c                 K   s"   t t| dd d | dd d S )Nr   r   r   )r=   r   r   rB   rB   rC   parse_pubsub_numsub  s   "rD  c                 K   s   t | tr| S t| dkS r   r:   rE   r*   r   rB   rB   rC   parse_client_kill   s   
rF  c                 K   s   | d u rd S t | dd}ttt|d |d< ttt|d |d< t|d |d< g g }}|d dD ]}d|v rB|| q6|| q6||d< ||d< d	|d v |d
< |S )NTr   r   	passwordscommandsr  @
categoriesonenabled)r   r=   r   r*   rN   r   )rJ   r   rW   rH  rJ  r  rB   rB   rC   parse_acl_getuser&  s   
rM  c                 K   sr   | d u rd S t | tr3g }| D ]!}t|dd}|dd}t||d< t|d |d< || q|S t| }|S )NTzclient-info zage-seconds)r:   r=   r   rc   parse_client_infor   r   r  )rJ   r   rW   loglog_dataclient_inforB   rB   rC   parse_acl_log>  s   
rS  c                 C   sL   i }|  d}|D ]}| d\}} | ||< q	dD ]
}t|| ||< q|S )zg
    Parsing client-info in ACL Log in following format.
    "key1=value1 key2=value2 key3=value3"
    r  r   >   	qbuf-freedbr  ageoblollsubidleomempsubqbufmulti)rN   rE   )r   rR  infosr   r   int_keyrB   rB   rC   rO  P  s   

rO  c                 C   s   t | tr| dS NT)r:   r    rI   rB   rB   rC   parse_module_resultn  s   
rb  c                   @      e Zd ZdefddZdS )ResponseCallbackProtocolrJ   c                 K      d S r8   rB   rV   rJ   r   rB   rB   rC   __call__u     z!ResponseCallbackProtocol.__call__Nri   rj   rk   r   rg  rB   rB   rB   rC   rd  t      rd  c                   @   rc  )AsyncResponseCallbackProtocolrJ   c                       d S r8   rB   rf  rB   rB   rC   rg  z     z&AsyncResponseCallbackProtocol.__call__Nri  rB   rB   rB   rC   rk  y  rj  rk  _Rc                4   @   s$  e Zd ZU dZi edeedeedeeddd edeed	e	ed
e
eddd eddd edeeddd edeedeedeeddd i ddd dedededdd de
ded e
d!e
d"d#d d$ed%ed&ed'ed(ed)e
d*d+d i d,e
d-e
d.d/d d0d1d d2e
d3e
d4e
d5ed6d7d d8e
d9ed:e
d;e
d<e
d=e
d>e
d?ei d@edAe
dBe
dCedDdEd dFdGd dHedIedJdKd dLedMedNedOe
dPedQedRedSei dTdUd dVedWdXd dYedZd[d d\e d]d^d d_e
d`e
daedbe!dce"dde#dee
dfe
dge$dhe
i die$djdkd dle%dmedne
doe dpdqd dre&dse
dteduedve
dwe'dxe'dye(dze)d{e*d|e+iZ,e-e.e/e0f e1f e2d}< e3d~e/fddZ4ddddddddddddddddddddddddddde/dede.e/ef de5e/ de5e de5e de5e de5e6ee.ee0f f  de5e7 de5e/ de/de/dededede5e/ de5e/ de/de5e/ dede5e dedede5e/ de5e/ f2ddZ8dd Z9dd Z:de;de;fddZ<de/de1fddZ=	d&dede5e/ ddfddZ>ddddde?dge.e@eAe@ f f deBde5e/ dede5e f
ddZC					d'deBde5e dede5e de5eDeE  deEfddńZFd(ddȄZGd)dd˄ZHd*dd̈́ZIde;de;fddτZJddф ZKdZLeMfde@ddfddՄZNddׄ ZOddل ZPdeQde.e/e0f fdd݄ZRd+de5e/ deAfddZSde/deAfddZTdeAfddZUde/deAfddZVdeAfddZWd+de5e deAfddZXdeAfddZYdeAfddZZdeAfddZ[										d,de/dedede5e.e/e\e/ f  de5e.e/e\e/ f  de5e\e/  de5e\e/  de5e\eB  dedededeAfddZ]deAfddZ^deAfd dZ_deAfddZ`deAfddZade/deAfddZb				d-d	e5e/ d
e5e/ de5e/ de5e deAf
ddZcd+d
e5e/ deAfddZddeAfddZedeAfddZfde/deAfddZgd.dededeAfddZhdedeAfddZideAfddZjdeAfdd Zkd/d"e/deAfd#d$Zlde/d%emdeAfd&d'ZndeAfd(d)ZodeAfd*d+ZpdeAfd,d-Zqd.eBdeAfd/d0Zrd%emdeAfd1d2Zsd.d3edeAfd4d5Ztd.d3edeAfd6d7Zud8ed9edeAfd:d;Zvd+d<e5e/ deAfd=d>ZwdeAfd?d@Zx			d0de/dedeydAededBedCedDe5e/ deAfdEdFZzdGe/d.eBdeAfdHdIZ{deAfdJdKZ|d+d.eBdLe5e deAfdMdNZ}deAfdOdPZ~deAfdQdRZdeAfdSdTZdUe/deAfdVdWZdUe/deAfdXdYZdeAfdZd[Zde/d\e/ded]edeAf
d^d_Zde/deAfd`daZdUe/deAfdbdcZde/dde/d%emdeAfdedfZdUe/deAfdgdhZd1diedjeddfdkdlZ	d2de5e/ de5e deAfdmdnZd+doe5e deAfdpdqZdeAfdrdsZdeAfdtduZdeAfdvdwZdxededeAfdydzZd.eBd%emdeAfd{d|Z	d2d.eBd}e5e d~e5e deAfddZ	d+d.eBde5e/ ddfddZde/deBdeBdeAfddZ		d2d.eBded}e5e d~e5e deAf
ddZd3deBdedeAfddZd3deBdedeAfddZdeBdeAfddZdeBdeAfddZdeBdeAfddZdeBdedeAfddZdeBdedeAfddZdeBdeAfddZdeBdedeAfddZd.eBd}ed~edeAfddZdeBd%emdeAfddZd3deBdedeAfddZd3deBdedeAfddZd4deBdedeAfddZd/d"edeAfddZdeydemdeAfddZde6eemf deAfddZde6eemf deAfddZdeBdedeAfddZdeBdeAfddZdeBdedeAfddZdeBdedeAfddZdeBded%emdeAfddÄZdeBdeAfdĐdńZdeAfdƐdǄZdeBdeBdeAfdʐd˄ZdeBdeBdeAfd̐d̈́Z		d1deBded%emdCededeAfdАdфZ					d5deBd%emde5e de5e dedededeAfdאd؄ZdeBded%edeAfdِdڄZdeBde.eejf d%emdeAfdېd܄ZdeBd%emdeAfdݐdބZdeBded%emdeAfdߐdZdeBdeAfddZd6deBd}ed~edeAfddZdeBdeAfddZdeBdeAfddZdeBdeAfddZdeBdeAfddZd7deydedeAfddZÐd7deydedeAfddZĐd7deBdeBdedeAfddZdeBdedeAfddZdeBde/demd%emdeAf
ddZdeBdeAfddZdeBdeAfddZdeBdemdeAfd dZdeBd%emdeAfddZdeBd}ed~edeAfddZdeBded%emdeAfddZdeBded%emdeAfdd	ZdeBd}ed~edeAfd
dZdeBdeAfddZАdeBdeBdeAfddZdeBdemdeAfddZdeBd%emdeAfddZ			d8deBd%emde5e de5e de5e deAfddZ								d9deBd}e5e doe5e de5eB de5ey dedede5eB dedeAfddZ				d:d ed!e5e de5e d
e5e/ deAf
d"d#Z			d8d!e5e de5e d
e5e/ defd$d%Z			d;deBd ed!e5e de5e deAf
d&d'Z	d2deBd!e5e de5e defd(d)Z			d;deBd ed!e5e de5e deAf
d*d+Z	d2de/d!e5e de5e defd,d-ZdddefdeBd ed!e5e de5e d.e.eDe?f deAfd/d0ZddefdeBd!e5e de5e d.e.eDe?f def
d1d2ZdeBdemdeAfd3d4ZdeBdeAfd5d6ZdeydemdeAfd7d8ZdeBdeydemdeAfd9d:ZdeydemdeAfd;d<ZdeBdeydemdeAfd=d>ZdeBd%emdeAfd?d@ZdeBdeAfdAdBZdeBdeBd%emdeAfdCdDZd+deBde5e deAfdEdFZd+deBdGe5e deAfdHdIZdeBdemdeAfdJdKZdeydemdeAfdLdMZdeBdeydemdeAfdNdOZdeBdPedQedeAfdRdSZ	!		d<deBdTeeemf dUede5e dVedeAfdWdXZ					d=deBdPedYedZed[e.ee ee f d\e5e de5e d]e5e d^ed_edeAfd`daZdeBdQedeAfdbdcZ	d>deBdPedUedeedeAf
dfdgZdeBdPedYedeAfdhdiZdeBdPedeAfdjdkZdeBdPedUedeAfdldmZdeBdPedeAfdndoZdeBdeAfdpdqZdeBdeAfdrdsZdeBdeAfdtduZdeBdPedeAfdvdwZ 	d+deBdPedxe5e dye5e de5e dYe5e deAfdzd{Z	|	}	d?deBdxedyede5e deAf
d~dZ		d2deeBef de5e de5e deAfddZ			d@dPe/dYe/deeBef de5e de5e dedeAfddZ	}	|	dAdeBdyedxede5e deAf
ddZdBdeBdedVedeAfddZ				dCdeBde6eemf dededededeAfddZdeBdeAfddZdeBdxe	dye	deAfddZ
deBded%emdeAfddZ	d+deBde.eeB e6eef f de5e/ deAfddZdeBdxemdyemdeAfddZd+deBde5e deAfddZd+deBde5e deAfddZd7deydedeAfddZd7deydedeAfddZddefdeBd}ed~ededed.e.eDe?f deAfddZ		d2deBdxemdyemd}e5e doe5e deAfddZ		d2deBdyemdxemd}e5e doe5e deAfddZdddefdeBdxe	dye	d}e5e doe5e ded.e.eDe?f deAfddZdeBd%emdeAfddZdeBdemdeAfddZdeBdxemdyemdeAfddZdeBdxedyedeAfddZdeBdxe	dye	deAfddZdefdeBd}ed~eded.e.eDe?f deAfddZdddefdeBdxe	dye	d}e5e doe5e ded.e.eDe?f deAfddZdeBd%emdeAfddZde/d%emdeAfddZ	d+deBde.eeB e6eef f de5e/ deAfddZ 	d+de/deBde.eeB e6eef f de5e/ deAf
ddZ!deBdemdeAfddZ"deBdeAfdĐdńZ#deBdeBdeAfdƐdǄZ$deBdedeAfdȐdɄZ%deBd.edeAfdʐd˄Z&deBd.edeAfd̐d̈́Z'deBdeAfdΐdτZ(d3deBd.ededeAfdАdфZ)d4deBd.ededeAfdҐdӄZ*deBdeAfdԐdՄZ+deBdeAfd֐dׄZ,			d8deBd.e5e d%e5em de5e6e-emf  deAf
dؐdلZ.deBd.ed%emdeAfdڐdۄZ/deBde6e-emf deAfdܐd݄Z0deBdeeB dedeAfdސd߄Z1deBdeAfddZ2deBd.edeAfddZ3de4demdeAfddZ5d/d"edeAfddZ6deAfddZ7de4deAfddZ8de/de/deAfddZ9de:dedemdeAfddZ;de/dedemdeAfddZ<de/deAfddZ=deAfddZ>deAfddZ?de:deAfdd Z@de:ddfddZAdeBdemdeAfddZB	d+deBdedede5e/ deAf
d	d
ZCdeBdedeAfddZDdeBdedeAfddZE								dDdeBdededede5e/ dededede5e de5e/ de5eB de5eB deAfddZF								dDdeBdedede5e/ dededede5e de5e/ de5eB de5eB deAfddZGde/demde5em deAfddZHde/deAfd d!ZIde/deAfd"d#ZJdeAfd$d%ZKdS (E  r3   a&  
    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 SETNXa  BITCOUNT 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 ZREMRANGEBYSCOREzINCRBYFLOAT HINCRBYFLOATzLPUSH RPUSHc                 C   s   t | tr| pt| dkS r   rE  r   rB   rB   rC   r7    r   zRedis.<lambda>SORTzZSCORE ZINCRBY GEODISTzuFLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE READONLY READWRITE RENAME SAVE SELECT SHUTDOWN SLAVEOF SWAPDB WATCH UNWATCH zBLPOP BRPOPc                 C   s   | rt | pd S r8   )tuplero  rB   rB   rC   r7    r>  zSDIFF SINTER SMEMBERS SUNIONc                 C   s   | rt | pt  S r8   )r   ro  rB   rB   rC   r7        z?ZPOPMAX ZPOPMIN ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCOREzBZPOPMIN BZPOPMAXc                 C   s"   | r| d | d t | d fpd S )Nr   r   r   r   ro  rB   rB   rC   r7    s   " zZRANK ZREVRANKzXREVRANGE XRANGEzXREAD XREADGROUPzBGREWRITEAOF BGSAVEc                 C      dS ra  rB   ro  rB   rB   rC   r7    r;  ACL CATc                 C   r   r8   r=   r   r*   ro  rB   rB   rC   r7        ACL DELUSERACL GENPASSACL GETUSERACL LISTc                 C   r   r8   ru  ro  rB   rB   rC   r7    rv  ACL LOADACL LOGACL SAVEACL SETUSER	ACL USERSc                 C   r   r8   ru  ro  rB   rB   rC   r7    rv  
ACL WHOAMICLIENT GETNAME	CLIENT IDCLIENT KILLCLIENT LISTCLIENT SETNAMECLIENT UNBLOCKc                 C   s   | rt | dkp	dS )Nr   Fr   ro  rB   rB   rC   r7        CLIENT PAUSEzCLUSTER ADDSLOTSzCLUSTER COUNT-FAILURE-REPORTSc                 C      t | S r8   r   r9  rB   rB   rC   r7        zCLUSTER COUNTKEYSINSLOTc                 C   r  r8   r   r9  rB   rB   rC   r7    r  zCLUSTER DELSLOTSzCLUSTER FAILOVERzCLUSTER FORGETzCLUSTER INFOzCLUSTER KEYSLOTc                 C   r  r8   r   r9  rB   rB   rC   r7    r  zCLUSTER MEETzCLUSTER NODESzCLUSTER REPLICATEzCLUSTER RESETzCLUSTER SAVECONFIGzCLUSTER SET-CONFIG-EPOCHzCLUSTER SETSLOTzCLUSTER SLAVES
CONFIG GETCONFIG RESETSTAT
CONFIG SETDEBUG OBJECTGEOHASHc                 C   r   r8   ru  ro  rB   rB   rC   r7    rv  GEOPOSc                 C   s   t tdd | S )Nc                 S   s$   | d urt | d t | d fS d S r   r   r5  rB   rB   rC   r7    r@  z Redis.<lambda>.<locals>.<lambda>)r=   r   ro  rB   rB   rC   r7    s    	GEORADIUSGEORADIUSBYMEMBERHGETALLc                 C   s   | rt | pi S r8   r   ro  rB   rB   rC   r7    r>  HSCANINFOLASTSAVEMEMORY PURGEMEMORY STATSMEMORY USAGEMODULE LOADMODULE UNLOADMODULE LISTc                 C   r   )Nc                 S   s   g | ]}t |qS rB   r   )rq   mrB   rB   rC   r     r  z"Redis.<lambda>.<locals>.<listcomp>rB   ro  rB   rB   rC   r7    rv  OBJECTPINGc                 C   r   )NPONGr  ro  rB   rB   rC   r7        PUBSUB NUMSUB	RANDOMKEYc                 C   s   | r| pd S r8   rB   ro  rB   rB   rC   r7    r  SCANSCRIPT EXISTSc                 C   r   r8   )r=   r   boolro  rB   rB   rC   r7    rv  SCRIPT FLUSHSCRIPT KILLSCRIPT LOAD SENTINEL GET-MASTER-ADDR-BY-NAMESENTINEL MASTERSENTINEL MASTERSSENTINEL MONITORSENTINEL REMOVESENTINEL SENTINELSSENTINEL SETSENTINEL SLAVESSETc                 C   s   | ot | dkS r   r  ro  rB   rB   rC   r7     r>  SLOWLOG GETSLOWLOG LENSLOWLOG RESETSSCANTIMEc                 C   r4  r   r   r9  rB   rB   rC   r7    r8  XCLAIMXGROUP CREATEXGROUP DELCONSUMERXGROUP DESTROYXGROUP SETIDXINFO CONSUMERSXINFO GROUPSXINFO STREAMXPENDINGZADDZSCANresponse_callbacksurlc                 K   s   t j|f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://` 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)clsr  r   r  rB   rB   rC   r    s   )
zRedis.from_url	localhosti  r   Nzutf-8strictFrequired)hostr   rU  passwordsocket_timeoutsocket_connect_timeoutsocket_keepalivesocket_keepalive_optionsr  unix_socket_pathencodingencoding_errorsr  retry_on_timeoutsslssl_keyfilessl_certfilessl_cert_reqsssl_ca_certsssl_check_hostnamemax_connectionssingle_connection_clienthealth_check_intervalclient_nameusernamer  r   rU  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  c                C   s   |	s=|||||||||||d}|
d ur| |
td n| |||||d |r6| t|||||d tdi |}	|	| _|| _d | _t| jj	| _
d S )N)rU  r  r  r  r  r  r  r  r  r  r  )pathconnection_class)r  r   r  r  r  )r  r  r  r  r  r  rB   )rg   r   r   r   r  r  
connectionrS   r`   RESPONSE_CALLBACKSr  )rV   r  r   rU  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   rB   rB   rC   rZ   A  sT   

zRedis.__init__c                 C   s   | j j d| jdS )N<>)r`   ri   r  rV   rB   rB   rC   __repr__  rf   zRedis.__repr__c                 C      |    S r8   )
initialize	__await__r  rB   rB   rC   r    r   zRedis.__await__rV   r7   c                    s*   | j r| jd u r| jdI d H | _| S )N_)r  r  r  get_connectionr  rB   rB   rC   r    s   zRedis.initializer  rP   c                 C   s   || j |< dS )zSet a custom Response CallbackN)r  )rV   r  rP   rB   rB   rC   set_response_callback     zRedis.set_response_callbackTtransaction
shard_hintPipelinec                 C   s   t | 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.
        )r  r  r  )rV   r  r  rB   rB   rC   pipeline  s   
zRedis.pipeline)r  value_from_callablewatch_delayfuncwatchesr  r  c          	   	      s   |  d|4 I dH L}	 z0|r|j| I dH  ||}t|r&|I dH }| I dH }|r1|n|W W  d  I dH  S  tyV   |durT|dkrTt|I dH  Y qw 1 I dH s]w   Y  dS )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.
        TNr   )r  watchinspectisawaitableexecuter&   asynciosleep)	rV   r  r  r  r  r  pipe
func_value
exec_valuerB   rB   rC   r    s$   


zRedis.transaction皙?r   timeoutr  blocking_timeout
lock_classc                 C   s    |du r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)r  r  r  thread_localr'   )rV   r   r  r  r  r  r  rB   rB   rC   lock  s   4z
Redis.lockPubSubc                 K   s   t | jfi |S )z
        Return a Publish/Subscribe object. With this object, you can
        subscribe to channels and listen for messages that get published to
        them.
        )r  r  )rV   r   rB   rB   rC   pubsub     zRedis.pubsubMonitorc                 C   
   t | jS r8   )r	  r  r  rB   rB   rC   monitor     
zRedis.monitorc                 C   s   | j | jddS )NT)r  r  )r`   r  r  rB   rB   rC   client  s   zRedis.clientc                    s   |   I d H S r8   )r  r  rB   rB   rC   
__aenter__  s   zRedis.__aenter__c                       |   I d H  d S r8   )closerV   exc_type	exc_value	tracebackrB   rB   rC   	__aexit__     zRedis.__aexit__zUnclosed Redis client	_warningsc                 C   sB   | j d ur|jd| t| d | | jd}t | d S d S )NzUnclosed client session )source)r  message)r  warnResourceWarning_DEL_MESSAGEr  get_event_loopcall_exception_handler)rV   r  contextrB   rB   rC   __del__$  s   
zRedis.__del__c                    s,   | j }|rd | _ | j|I d H  d S d S r8   )r  r  releaserV   connrB   rB   rC   r  .  s   zRedis.closec              
      s,  |   I dH  | j}|d }| jp|j|fi |I dH }zjz#|j| I dH  | j||fi |I dH W W | jsB||I dH  S S  ttfy } z8|	 I dH  |j
r[t|ts\ |j| I dH  | j||fi |I dH W  Y d}~W | js||I dH  S S d}~ww | js||I dH  w w )z.Execute a command and return a parsed responseNr   )r  r  r  r  send_commandparse_responser!  r   r%   
disconnectr  r:   )rV   r6   r   poolcommand_namer#  erB   rB   rC   execute_command5  s2   &zRedis.execute_commandr  r(  c                    s   z	|  I dH }W n ty   t|v r|t  Y S  w || jv r>tt|}| j| |fi |}t|r<|I dH S |S |S )z'Parses a response from the Redis serverN)read_responser$   r.   r  r   r<   r  r  )rV   r  r(  r   rJ   retvalrB   rB   rC   r%  H  s   

zRedis.parse_responsecategoryc                 C   s    |r|gng }| j dg|R  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.
        rt  r*  )rV   r-  piecesrB   rB   rC   acl_cat\  s   zRedis.acl_catc                 C      |  d|S )z-Delete the ACL for the specified ``username``rw  r.  rV   r  rB   rB   rC   acl_deluserg     zRedis.acl_deluserc                 C   
   |  dS )z Generate a random password valuerx  r.  r  rB   rB   rC   acl_genpassk     
zRedis.acl_genpassc                 C   r1  )zz
        Get the ACL details for the specified ``username``.

        If ``username`` does not exist, return None
        ry  r.  r2  rB   rB   rC   acl_getusero  s   zRedis.acl_getuserc                 C   r5  )z'Return a list of all ACLs on the serverrz  r.  r  rB   rB   rC   acl_listw  r7  zRedis.acl_listcountc                 C   s:   g }|durt |tstd|| | jdg|R  S )zl
        Get ACL logs as a list.
        :param int count: Get logs[0:count].
        :rtype: List.
        Nz ACL LOG count must be an integerr|  )r:   rE   r   r   r*  )rV   r:  r6   rB   rB   rC   acl_log{  s   

zRedis.acl_logc                 C   s   dg}| j dg|R  S )z:
        Reset ACL logs.
        :rtype: Boolean.
        s   RESETr|  r.  rV   r6   rB   rB   rC   acl_log_reset  s   zRedis.acl_log_resetc                 C   r5  )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.
        r{  r.  r  rB   rB   rC   acl_load     
zRedis.acl_loadc                 C   r5  )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.
        r}  r.  r  rB   rB   rC   acl_save  r?  zRedis.acl_saverL  nopassrG  hashed_passwordsrJ  rH  r5   reset
reset_keysreset_passwordsc                 C   s  | j  }|g}|	r|d |
r|d |r|d |r%|d n|d |s.|r4|r4td|rpt|g }t|D ]0\}}||}|drY|d|d	d
   q?|drj|d|d	d
   q?td| |rt|g }t|D ]0\}}||}|dr|d|d	d
   q{|dr|d|d	d
   q{td| |r|d |r|D ]K}||}|dr|| q|dr|d|d	d
   q|dr|| q|dr|d|d	d
   qtd|j|dd d|r0|D ]&}||}|ds)|ds)td|j|dd d|| q	|rE|D ]}||}|d|  q5| j	dg|R  S )aA  
        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
        ``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.
        s   resets	   resetkeyss	   resetpasss   ons   offz@Cannot set 'nopass' and supply 'passwords' or 'hashed_passwords'   +s   >%sr   N   -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 removes   nopasss   +@s   +@%ss   -@s   -@%sz
Category "Tforcez"" must be prefixed with "+" or "-"z	Command "s   ~%sr~  )
r  get_encoderr   r   rD   	enumerateencoder   decoder*  )rV   r  rL  rA  rG  rB  rJ  rH  r5   rC  rD  rE  encoderr/  converted_passwordsr   raw_passwordr  parsed_hashed_passwordsraw_hashed_passwordhashed_passwordraw_categoryr-  raw_cmdcmdraw_keyr   rB   rB   rC   acl_setuser  s   
I



















zRedis.acl_setuserc                 C   r5  )z5Returns a list of all registered users on the server.r  r.  r  rB   rB   rC   	acl_usersG  r7  zRedis.acl_usersc                 C   r5  )z+Get the username for the current connectionr  r.  r  rB   rB   rC   
acl_whoamiK  r7  zRedis.acl_whoamic                 C   r5  )zBTell the Redis server to rewrite the AOF file from data in memory.BGREWRITEAOFr.  r  rB   rB   rC   bgrewriteaofO  r7  zRedis.bgrewriteaofc                 C   r5  )z
        Tell the Redis server to save its data to disk.  Unlike save(),
        this method is asynchronous and returns immediately.
        BGSAVEr.  r  rB   rB   rC   bgsaveS     
zRedis.bgsaveaddressc                 C   r1  )z/Disconnects the client at ``address`` (ip:port)r  r.  )rV   r`  rB   rB   rC   client_killZ  r4  zRedis.client_kill_id_typer(  skipmec                 C   s   g }|durd}t | |vrtd||d|f |dur8t|ts+td|r3|d n|d |durC|d|f |durN|d	|f |sTtd
| jdg|R  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)normalr   r   r  z CLIENT KILL type must be one of    TYPEz!CLIENT KILL skipme must be a bool)   SKIPMEs   YES)rg     NOs   IDs   ADDRzVCLIENT KILL <filter> <value> ... ... <filter> <value> must specify at least one filterr  )r<   lowerr   r@   r:   r  r*  )rV   rb  rc  r(  rd  r6   client_typesrB   rB   rC   client_kill_filter^  s*   

zRedis.client_kill_filterc                 C   sD   	 |durd}t | |vrtd|| dd|S | d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)
        N)re  r   replicar  z!CLIENT LIST _type must be one of r  rf  )r<   ri  r   r*  )rV   rc  rj  rB   rB   rC   client_list  s   
zRedis.client_listc                 C   r5  )z#Returns the current connection namer  r.  r  rB   rB   rC   client_getname  r7  zRedis.client_getnamec                 C   r5  )z!Returns the current connection idr  r.  r  rB   rB   rC   	client_id  r7  zRedis.client_idc                 C   r1  )z Sets the current connection namer  r.  rV   r   rB   rB   rC   client_setname  r4  zRedis.client_setnamero  errorc                 C   s$   dt |g}|r|d | 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.
        r  s   ERROR)rE   r   r*  )rV   ro  rr  r6   rB   rB   rC   client_unblock  s   

zRedis.client_unblockc                 C   s"   t |ts	td| dt|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 integerr  )r:   rE   r   r*  r<   )rV   r  rB   rB   rC   client_pause  s   
zRedis.client_pausec                 C   r5  )zDDisables read queries for a connection to a Redis Cluster slave node	READWRITEr.  r  rB   rB   rC   	readwrite  r7  zRedis.readwritec                 C   r5  )zEEnables read queries for a connection to a Redis Cluster replica nodeREADONLYr.  r  rB   rB   rC   readonly  r7  zRedis.readonly*patternc                 C   r1  )z=Return a dictionary of configuration based on the ``pattern``r  r.  rV   rz  rB   rB   rC   
config_get  r4  zRedis.config_getr   c                 C      |  d||S )z'Set config item ``name`` with ``value``r  r.  rV   r   r   rB   rB   rC   
config_set  r  zRedis.config_setc                 C   r5  )zReset runtime statisticsr  r.  r  rB   rB   rC   config_resetstat  r7  zRedis.config_resetstatc                 C   r5  )zERewrite config file with the minimal change to reflect running configzCONFIG REWRITEr.  r  rB   rB   rC   config_rewrite  r7  zRedis.config_rewritec                 C   r5  )z2Returns the number of keys in the current databaseDBSIZEr.  r  rB   rB   rC   dbsize  r7  zRedis.dbsizer   c                 C   r1  )z;Returns version specific meta information about a given keyr  r.  )rV   r   rB   rB   rC   debug_object  r4  zRedis.debug_objectc                 C   r1  )z$Echo the string back from the serverECHOr.  )rV   r   rB   rB   rC   echo  r4  z
Redis.echoasynchronousc                 C   $   g }|r	| d | jdg|R  S )z
        Delete all keys in all databases on the current host.

        ``asynchronous`` indicates whether the operation is
        executed asynchronously by the server.
           ASYNCFLUSHALLr   r*  rV   r  r6   rB   rB   rC   flushall     
zRedis.flushallc                 C   r  )z
        Delete all keys in the current database.

        ``asynchronous`` indicates whether the operation is
        executed asynchronously by the server.
        r  FLUSHDBr  r  rB   rB   rC   flushdb  r  zRedis.flushdbr   secondc                 C   r}  )zSwap two databasesSWAPDBr.  )rV   r   r  rB   rB   rC   swapdb  r  zRedis.swapdbsectionc                 C   s   |du r	|  dS |  d|S )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  r.  )rV   r  rB   rB   rC   r     s   

z
Redis.infoc                 C   r5  )zy
        Return a Python datetime object representing the last time the
        Redis database was saved to disk
        r  r.  r  rB   rB   rC   lastsave  r_  zRedis.lastsavedestination_dbcopyreplaceauthc	           
      C   s~   t |g }|stdg }	|r|	d |r|	d |r'|	d |	| |	d |	| | jd||d||g|	R  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 keys   COPYs   REPLACEs   AUTHs   KEYSMIGRATErN  )rD   r   r   r@   r*  )
rV   r  r   r5   r  r  r  r  r  r/  rB   rB   rC   migrate  s$   






zRedis.migrater}   c                 C   s   | j d|||dS )z8Return the encoding, idletime, or refcount about the keyr  )r}   r.  )rV   r}   r   rB   rB   rC   object:     zRedis.objectc                 C   r5  )z#Return a dictionary of memory statsr  r.  r  rB   rB   rC   memory_stats>  r7  zRedis.memory_statssamplesc                 C   s0   g }t |tr|d|g | jd|g|R  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.
        s   SAMPLESr  )r:   rE   r@   r*  )rV   r   r  r6   rB   rB   rC   memory_usageB  s   	
zRedis.memory_usagec                 C   r5  )z:Attempts to purge dirty pages for reclamation by allocatorr  r.  r  rB   rB   rC   memory_purgeP  r7  zRedis.memory_purgec                 C   r5  )zPing the Redis serverr  r.  r  rB   rB   rC   r)  T  r7  z
Redis.pingc                 C   r5  )zm
        Tell the Redis server to save its data to disk,
        blocking until the save is complete
        SAVEr.  r  rB   rB   rC   saveX  r_  z
Redis.saveservice_namec                 C   r1  )z:Returns a (host, port) pair for the given ``service_name``r  r.  rV   r  rB   rB   rC    sentinel_get_master_addr_by_name_  r4  z&Redis.sentinel_get_master_addr_by_namec                 C   r1  )z<Returns a dictionary containing the specified masters state.r  r.  r  rB   rB   rC   sentinel_masterc  r4  zRedis.sentinel_masterc                 C   r5  )z>Returns a list of dictionaries containing each master's state.r  r.  r  rB   rB   rC   sentinel_mastersg  r7  zRedis.sentinel_mastersipr   c                 C      |  d||||S )z,Add a new master to Sentinel to be monitoredr  r.  )rV   r   r  r   r   rB   rB   rC   sentinel_monitork  r  zRedis.sentinel_monitorc                 C   r1  )z*Remove a master from Sentinel's monitoringr  r.  rp  rB   rB   rC   sentinel_removeo  r4  zRedis.sentinel_removec                 C   r1  )z0Returns a list of sentinels for ``service_name``r  r.  r  rB   rB   rC   sentinel_sentinelss  r4  zRedis.sentinel_sentinelsoptionc                 C      |  d|||S )z5Set Sentinel monitoring parameters for a given masterr  r.  )rV   r   r  r   rB   rB   rC   sentinel_setw     zRedis.sentinel_setc                 C   r1  )z-Returns a list of slaves for ``service_name``r  r.  r  rB   rB   rC   sentinel_slaves{  r4  zRedis.sentinel_slavesr  nosavec                 C   s\   |r|rt ddg}|r|d |r|d z
| j|  W td ty-   Y dS w )an  Shutdown the Redis server.  If Redis has persistence configured,
        data will be flushed before shutdown.  If the "save" option is set,
        a data flush will be attempted even if there is no persistence
        configured.  If the "nosave" option is set, no data flush will be
        attempted.  The "save" and "nosave" options cannot both be set.
        z+SHUTDOWN save and nosave cannot both be setSHUTDOWNr  NOSAVENzSHUTDOWN seems to have failed.)r   r   r*  r   r#   )rV   r  r  r6   rB   rB   rC   shutdown  s   

zRedis.shutdownc                 C   s,   |du r|du r|  dddS |  d||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.
        NSLAVEOFrh  s   ONEr.  )rV   r  r   rB   rB   rC   slaveof  s   zRedis.slaveofnumc                 C   s8   dg}|dur| | | jjdd}| j|d|iS )zw
        Get the entries from the slowlog. If ``num`` is specified, get the
        most recent ``num`` items.
        r  Nr  F)r   r  connection_kwargsrc   r*  )rV   r  r6   r  rB   rB   rC   slowlog_get  s   
zRedis.slowlog_getc                 C   r5  )z&Get the number of items in the slowlogr  r.  r  rB   rB   rC   slowlog_len  r7  zRedis.slowlog_lenc                 C   r5  )zRemove all items in the slowlogr  r.  r  rB   rB   rC   slowlog_reset  r7  zRedis.slowlog_resetc                 C   r5  )z
        Returns the server time as a 2-item tuple of ints:
        (seconds since epoch, microseconds into this second).
        r  r.  r  rB   rB   rC   time  r_  z
Redis.timenum_replicasc                 C   r}  )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.
        WAITr.  )rV   r  r  rB   rB   rC   wait     z
Redis.waitc                 C   r}  )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``.
        APPENDr.  )rV   r   r   rB   rB   rC   r        zRedis.appendstartendc                 C   sf   |g}|dur|dur| | | | n|dur|du s&|dur*|du r*td| jdg|R  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   r   r*  )rV   r   r  r  paramsrB   rB   rC   bitcount  s   
 zRedis.bitcountdefault_overflowBitFieldOperationc                 C   s   t | ||dS )z
        Return a BitFieldOperation instance to conveniently construct one or
        more bitfield operations on ``key``.
        )r  )r  )rV   r   r  rB   rB   rC   bitfield  r  zRedis.bitfield	operationdestc                 G      | j d||g|R  S )z|
        Perform a bitwise operation using ``operation`` between ``keys`` and
        store the result in ``dest``.
        BITOPr.  )rV   r  r  r5   rB   rB   rC   bitop  s   zRedis.bitopbitc                 C   s`   |dvrt d||g}|dur|| |dur|| n|dur't d| jdg|R  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.
        r   zbit must be 0 or 1Nz0start argument is not set, when end is specifiedBITPOSr   r   r*  )rV   r   r  r  r  r  rB   rB   rC   bitpos  s   

zRedis.bitposr   amountc                 C      |  ||S )
        Decrements the value of ``key`` by ``amount``.  If no key exists,
        the value will be initialized as 0 - ``amount``
        )decrbyrV   r   r  rB   rB   rC   decr  s   z
Redis.decrc                 C   r}  )r  DECRBYr.  r  rB   rB   rC   r       zRedis.decrbynamesc                 G      | j dg|R  S )z.Delete one or more keys specified by ``names``DELr.  rV   r  rB   rB   rC   delete  r  zRedis.deletec                 C   r1  )z
        Return a serialized version of the value stored at the specified key.
        If key does not exist a nil bulk reply is returned.
        DUMPr.  rp  rB   rB   rC   dump     z
Redis.dumpc                 G   r  )z*Returns the number of ``names`` that existEXISTSr.  r  rB   rB   rC   exists!  r  zRedis.existsr  c                 C   s&   t |tjrt| }| d||S )z
        Set an expire flag on key ``name`` for ``time`` seconds. ``time``
        can be represented by an integer or a Python timedelta object.
        EXPIREr:   rG   	timedeltarE   total_secondsr*  rV   r   r  rB   rB   rC   expire%  s   zRedis.expirewhenc                 C   s,   t |tjrtt| }| d||S )z
        Set an expire flag on key ``name``. ``when`` can be represented
        as an integer indicating unix time or a Python datetime object.
        EXPIREAT)r:   rG   rE   mod_timemktime	timetupler*  )rV   r   r  rB   rB   rC   expireat.  s   zRedis.expireatc                 C   r1  )zT
        Return the value at key ``name``, or None if the key doesn't exist
        GETr.  rp  rB   rB   rC   rc   7     z	Redis.getoffsetc                 C   r}  )z@Returns a boolean indicating the value of ``offset`` in ``name``GETBITr.  )rV   r   r  rB   rB   rC   getbit=  r  zRedis.getbitc                 C   r  )z
        Returns the substring of the string value stored at ``key``,
        determined by the offsets ``start`` and ``end`` (both are inclusive)
        GETRANGEr.  )rV   r   r  r  rB   rB   rC   getrangeA     zRedis.getrangec                 C   r}  )z{
        Sets the value at key ``name`` to ``value``
        and returns the old value at key ``name`` atomically.
        GETSETr.  r~  rB   rB   rC   getsetH  r  zRedis.getsetc                 C   r  )
        Increments the value of ``key`` by ``amount``.  If no key exists,
        the value will be initialized as ``amount``
        )incrbyr  rB   rB   rC   incrO  r  z
Redis.incrc                 C   r}  )r  INCRBYr.  r  rB   rB   rC   r  V  r  zRedis.incrby      ?c                 C   r}  )z
        Increments the value at key ``name`` by floating ``amount``.
        If no key exists, the value will be initialized as ``amount``
        INCRBYFLOATr.  r  rB   rB   rC   incrbyfloat_  r  zRedis.incrbyfloatc                 C   r1  )z+Returns a list of keys matching ``pattern``KEYSr.  r{  rB   rB   rC   r5   f  r4  z
Redis.keysr6   c                 G   s2   t ||}i }|sg |t< | jdg|R i |S )zJ
        Returns a list of values ordered identically to ``keys``
        MGET)rD   r.   r*  )rV   r5   r6   encoded_argsr   rB   rB   rC   mgetj  s
   
z
Redis.mgetmappingc                 C   .   g }|  D ]}|| q| jdg|R  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rT   r@   r*  rV   r	  rT   r  rB   rB   rC   msett  s   z
Redis.msetc                 C   r
  )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.
        MSETNXr  r  rB   rB   rC   msetnx  s   zRedis.msetnxc                 C   r}  )z;Moves the key ``name`` to a different Redis database ``db``MOVEr.  )rV   r   rU  rB   rB   rC   move  r  z
Redis.movec                 C   r1  )z!Removes an expiration on ``name``PERSISTr.  rp  rB   rB   rC   persist  r4  zRedis.persistc                 C   s*   t |tjrt| d }| d||S )z
        Set an expire flag on key ``name`` for ``time`` milliseconds.
        ``time`` can be represented by an integer or a Python timedelta
        object.
          PEXPIREr  r  rB   rB   rC   pexpire  s   zRedis.pexpirec                 C   sB   t |tjrt|jd }tt| d | }| d||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.
        r  	PEXPIREAT)r:   rG   rE   microsecondr  r  r  r*  )rV   r   r  msrB   rB   rC   	pexpireat  s   zRedis.pexpireattime_msc                 C   s,   t |tjrt| d }| d|||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
        r  PSETEXr  )rV   r   r  r   rB   rB   rC   psetex  s   zRedis.psetexc                 C   r1  )zEReturns the number of milliseconds until the key ``name`` will expirePTTLr.  rp  rB   rB   rC   pttl  r4  z
Redis.pttlc                 C   r5  )z Returns the name of a random keyr  r.  r  rB   rB   rC   	randomkey  r7  zRedis.randomkeysrcdstc                 C   r}  )z/
        Rename key ``src`` to ``dst``
        RENAMEr.  rV   r"  r#  rB   rB   rC   rename  s   zRedis.renamec                 C   r}  )z>Rename key ``src`` to ``dst`` if ``dst`` doesn't already existRENAMENXr.  r%  rB   rB   rC   renamenx  r  zRedis.renamenxttlabsttlc                 C   s8   |||g}|r| d |r| d | jdg|R  S )a  
        Create a key using the provided serialized value, previously obtained
        using DUMP.

        ``replace`` allows an existing key on ``name`` to be overridden. If
        it's not specified an error is raised on collision.

        ``absttl`` if True, specified ``ttl`` should represent an absolute Unix
        timestamp in milliseconds in which the key will expire. (Redis 5.0 or
        greater).
        REPLACEABSTTLRESTOREr  )rV   r   r)  r   r  r*  r  rB   rB   rC   restore  s   


zRedis.restoreexpxnxxxkeepttlc           	      C   s   ||g}|dur| d t|tjrt| }| | |dur:| d t|tjr5t| d }| | |rA| d |rH| d |rO| d | jdg|R  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)
        NEXPXr  NXXXKEEPTTLr  )r   r:   rG   r  rE   r  r*  )	rV   r   r   r/  r0  r1  r2  r3  r/  rB   rB   rC   r     s$   






z	Redis.setc                 C   s   |rdpd}|  d|||S )z
        Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
        indicating the previous value of ``offset``.
        r   r   SETBITr.  rV   r   r  r   rB   rB   rC   setbit  s   zRedis.setbitc                 C   s(   t |tjrt| }| d|||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.
        SETEXr  )rV   r   r  r   rB   rB   rC   setex  s   zRedis.setexc                 C   r}  )z?Set the value of key ``name`` to ``value`` if key doesn't existSETNXr.  r~  rB   rB   rC   setnx"  r  zRedis.setnxc                 C   r  )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.
        SETRANGEr.  r:  rB   rB   rC   setrange&     zRedis.setrangec                 C   r1  )z:Return the number of bytes stored in the value of ``name``STRLENr.  rp  rB   rB   rC   strlen3  r4  zRedis.strlenr   c                 C   r  )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.
        SUBSTRr.  rV   r   r  r  rB   rB   rC   substr7  r  zRedis.substrc                 G   r  )zs
        Alters the last access time of a key(s) ``*args``. A key is ignored
        if it does not exist.
        TOUCHr.  r<  rB   rB   rC   touch>     zRedis.touchc                 C   r1  )z@Returns the number of seconds until the key ``name`` will expireTTLr.  rp  rB   rB   rC   r)  E  r4  z	Redis.ttlc                 C   r1  )z Returns the type of key ``name``TYPEr.  rp  rB   rB   rC   rA  I  r4  z
Redis.typec                 G   r  )z.Unlink one or more keys specified by ``names``UNLINKr.  r  rB   rB   rC   unlinkM  r  zRedis.unlinkc                 C      | j dgt||fR  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.
        BLPOPr*  rD   rV   r5   r  rB   rB   rC   blpopR     zRedis.blpopc                 C   rO  )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.
        BRPOPrQ  rR  rB   rB   rC   brpop_  rT  zRedis.brpopc                 C   r  )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.
        
BRPOPLPUSHr.  )rV   r"  r#  r  rB   rB   rC   
brpoplpushl  s   	zRedis.brpoplpushindexc                 C   r}  )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
        LINDEXr.  )rV   r   rY  rB   rB   rC   lindexw  r  zRedis.lindexwhererefvaluec                 C   r  )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.
        LINSERTr.  )rV   r   r\  r]  r   rB   rB   rC   linsert  s   
zRedis.linsertc                 C   r1  )z&Return the length of the list ``name``LLENr.  rp  rB   rB   rC   llen  r4  z
Redis.llenc                 C   r1  )z5Remove and return the first item of the list ``name``LPOPr.  rp  rB   rB   rC   lpop  r4  z
Redis.lpopr   c                 G      | j d|g|R  S )z2Push ``values`` onto the head of the list ``name``LPUSHr.  rV   r   r   rB   rB   rC   lpush     zRedis.lpushc                 C   r}  )zDPush ``value`` onto the head of the list ``name`` if ``name`` existsLPUSHXr.  r~  rB   rB   rC   lpushx  r  zRedis.lpushxc                 C   r  )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
        LRANGEr.  rF  rB   rB   rC   lrange     zRedis.lrangec                 C   r  )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.
        LREMr.  )rV   r   r:  r   rB   rB   rC   lrem  s   
z
Redis.lremc                 C   r  )z.Set ``position`` of list ``name`` to ``value``LSETr.  )rV   r   rY  r   rB   rB   rC   lset  r  z
Redis.lsetc                 C   r  )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
        LTRIMr.  rF  rB   rB   rC   ltrim  rm  zRedis.ltrimc                 C   r1  )z4Remove and return the last item of the list ``name``RPOPr.  rp  rB   rB   rC   rpop  r4  z
Redis.rpopc                 C   r}  )z
        RPOP a value off of the ``src`` list and atomically LPUSH it
        on to the ``dst`` list.  Returns the value.
        	RPOPLPUSHr.  r%  rB   rB   rC   	rpoplpush  r  zRedis.rpoplpushc                 G   rd  )z2Push ``values`` onto the tail of the list ``name``RPUSHr.  rf  rB   rB   rC   rpush  rh  zRedis.rpushc                 C   r}  )zDPush ``value`` onto the tail of the list ``name`` if ``name`` existsRPUSHXr.  r~  rB   rB   rC   rpushx  r  zRedis.rpushxrankmaxlenc                 C   s\   ||g}|dur| d|g |dur| d|g |dur%| d|g | jdg|R  S )a   
        Get position of ``value`` within the list ``name``

         If specified, ``rank`` indicates the "rank" of the first element to
         return in case there are multiple copies of ``value`` in the list.
         By default, LPOS returns the position of the first occurrence of
         ``value`` in the list. When ``rank`` 2, LPOS returns the position of
         the second ``value`` in the list. If ``rank`` is negative, LPOS
         searches the list in reverse. For example, -1 would return the
         position of the last occurrence of ``value`` and -2 would return the
         position of the next to last occurrence of ``value``.

         If specified, ``count`` indicates that LPOS should return a list of
         up to ``count`` positions. A ``count`` of 2 would return a list of
         up to 2 positions. A ``count`` of 0 returns a list of all positions
         matching ``value``. When ``count`` is specified and but ``value``
         does not exist in the list, an empty list is returned.

         If specified, ``maxlen`` indicates the maximum number of list
         elements to scan. A ``maxlen`` of 1000 will only return the
         position(s) of items within the first 1000 entries in the list.
         A ``maxlen`` of 0 (the default) will scan the entire list.
        NRANKCOUNTMAXLENLPOSr@   r*  )rV   r   r   r|  r:  r}  r/  rB   rB   rC   lpos  s   z
Redis.lposbyrc   descalphar/  r   c
                 C   sR  |dur|du s|dur|du rt d|g}
|dur%|
d |
| |dur<|dur<|
d |
| |
| |durat|ttfrR|
d |
| n|D ]}|
d |
| qT|rh|
d |ro|
d |dur}|
d |
| |	r|rt|ttfst|d	k rt d
dt|i}nddi}| jdg|
R i |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``.

        N,``start`` and ``num`` must both be specifieds   BY   LIMITs   GET   DESCs   ALPHA   STOREr   zVwhen using "groups" the "get" argument must be specified and contain at least two keysr   rp  )r   r   r:   r;   r<   lenr*  )rV   r   r  r  r  rc   r  r  r/  r   r/  gr   rB   rB   rC   sort  s@    $










z
Redis.sortr  matchc                 C   sZ   |g}|dur| d|g |dur| d|g |dur$| d|g | jdg|R  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.
        N   MATCH   COUNTrf  r  r  )rV   r  r  r:  rc  r/  rB   rB   rC   scanO	  s   z
Redis.scanc                 C  sN   d}|dkr%| j |pd|||dI dH \}}|D ]}|V  q|dksdS dS )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.
        Nr   )r  r  r:  rc  )r  )rV   r  r:  rc  r  rW   drB   rB   rC   	scan_iterm	  s   zRedis.scan_iterc                 C   F   ||g}|dur| d|g |dur| d|g | jdg|R  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
        Nr  r  r  r  rV   r   r  r  r:  r/  rB   rB   rC   sscan	     zRedis.sscanc                 C  sN   d}|dkr%| j ||pd||dI dH \}}|D ]}|V  q|dksdS dS )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
        Nr   r  r  r:  )r  )rV   r   r  r:  r  rW   r  rB   rB   rC   
sscan_iter	  s   zRedis.sscan_iterc                 C   r  )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
        Nr  r  r  r  r  rB   rB   rC   hscan	  r  zRedis.hscanc                 C  sR   d}|dkr'| j ||pd||dI dH \}}| D ]}|V  q|dksdS dS )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
        Nr   r  )r  rT   )rV   r   r  r:  r  rW   r   rB   rB   rC   
hscan_iter	  s   zRedis.hscan_iterr   c                 C   sT   ||g}|dur| d|g |dur| d|g d|i}| jdg|R i |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
        Nr  r  r   r  r  )rV   r   r  r  r:  r   r/  r   rB   rB   rC   zscan	  s   zRedis.zscanc                 C  sP   d}|dkr&| j ||pd|||dI dH \}}|D ]}|V  q|dksdS dS )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
        Nr   )r  r  r:  r   )r  )rV   r   r  r:  r   r  rW   r  rB   rB   rC   
zscan_iter	  s   zRedis.zscan_iterc                 G   rd  )z Add ``value(s)`` to set ``name``SADDr.  rf  rB   rB   rC   sadd
  rh  z
Redis.saddc                 C   r1  )z-Return the number of elements in set ``name``SCARDr.  rp  rB   rB   rC   scard
  r4  zRedis.scardc                 G      t ||}| jdg|R  S )z3Return the difference of sets specified by ``keys``SDIFFrD   r*  rV   r5   r6   parsed_argsrB   rB   rC   sdiff
     
zRedis.sdiffc                 G      t ||}| jd|g|R  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.
        
SDIFFSTOREr  rV   r  r5   r6   r  rB   rB   rC   
sdiffstore 
     
zRedis.sdiffstorec                 G   r  )z5Return the intersection of sets specified by ``keys``SINTERr  r  rB   rB   rC   sinter(
  r  zRedis.sinterc                 G   r  )z
        Store the intersection of sets specified by ``keys`` into a new
        set named ``dest``.  Returns the number of keys in the new set.
        SINTERSTOREr  r  rB   rB   rC   sinterstore-
  r  zRedis.sinterstorec                 C   r}  )zDReturn a boolean indicating if ``value`` is a member of set ``name``	SISMEMBERr.  r~  rB   rB   rC   	sismember5
  r  zRedis.sismemberc                 C   r1  )z&Return all members of the set ``name``SMEMBERSr.  rp  rB   rB   rC   smembers9
  r4  zRedis.smembersc                 C   r  )z9Move ``value`` from set ``src`` to set ``dst`` atomicallySMOVEr.  )rV   r"  r#  r   rB   rB   rC   smove=
  r  zRedis.smovec                 C   &   |dur|gpg }| j d|g|R  S )z1Remove and return a random member of set ``name``NSPOPr.  )rV   r   r:  r6   rB   rB   rC   spopA
  s   z
Redis.spopnumberc                 C   r  )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+.
        NSRANDMEMBERr.  )rV   r   r  r6   rB   rB   rC   srandmemberF
  s   zRedis.srandmemberc                 G   rd  )z#Remove ``values`` from set ``name``SREMr.  rf  rB   rB   rC   sremQ
  rh  z
Redis.sremc                 G   r  )z.Return the union of sets specified by ``keys``SUNIONr  r  rB   rB   rC   sunionU
  r  zRedis.sunionc                 G   r  )z
        Store the union of sets specified by ``keys`` into a new
        set named ``dest``.  Returns the number of keys in the new set.
        SUNIONSTOREr  r  rB   rB   rC   sunionstoreZ
  r  zRedis.sunionstore	groupnameidsc                 G   r  )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.
        XACKr.  )rV   r   r  r  rB   rB   rC   xackc
  s   z
Redis.xackfieldsr  approximatec                 C   s   g }|dur&t |tr|dk rtd|d |r|d |t| || t |tr6t|dkr:td| D ]}|| q>| j	d|g|R  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

        Nr   z&XADD maxlen must be a positive integer   MAXLEN   ~r   z$XADD fields must be a non-empty dictXADD)
r:   rE   r   r   r<   rL   r  rT   r@   r*  )rV   r   r  r  r}  r  r/  r  rB   rB   rC   xaddl
  s   


z
Redis.xaddconsumernamemin_idle_timemessage_idsrZ  
retrycountrI  justidc                 C   s:  t |tr	|dk rtdt |ttfr|stdi }|||t|g}|t| |durAt |ts8td|dt|f |durWt |tsNtd|dt|f |durmt |tsdtd	|d
t|f |	r}t |	tsxtd|d |
rt |
tstd|d d|d< | j	dg|R i |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
        r   z3XCLAIM min_idle_time must be a non negative integerzLXCLAIM message_ids must be a non empty list or tuple of message IDs to claimNzXCLAIM idle must be an integers   IDLEzXCLAIM time must be an integers   TIMEz$XCLAIM retrycount must be an integers
   RETRYCOUNTzXCLAIM force must be a booleans   FORCEzXCLAIM justid must be a booleans   JUSTIDTr   r  )
r:   rE   r   r=   rq  r<   r@   r  r   r*  )rV   r   r  r  r  r  rZ  r  r  rI  r  r   r/  rB   rB   rC   xclaim
  s>   #






zRedis.xclaimc                 G   rd  )z
        Deletes one or more messages from a stream.
        name: name of the stream.
        *ids: message ids to delete.
        XDELr.  )rV   r   r  rB   rB   rC   xdel
     z
Redis.xdel$mkstreamc                 C   s$   d|||g}|r| d | 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.
        r  s   MKSTREAMr  )rV   r   r  r  r  r/  rB   rB   rC   xgroup_create
  s   	

zRedis.xgroup_createc                 C   r  )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
        r  r.  )rV   r   r  r  rB   rB   rC   xgroup_delconsumer
  rB  zRedis.xgroup_delconsumerc                 C   r}  )z|
        Destroy a consumer group.
        name: name of the stream.
        groupname: name of the consumer group.
        r  r.  rV   r   r  rB   rB   rC   xgroup_destroy
  r  zRedis.xgroup_destroyc                 C   r  )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.
        r  r.  )rV   r   r  r  rB   rB   rC   xgroup_setid
     zRedis.xgroup_setidc                 C   r}  )z
        Returns general information about the consumers in the group.
        name: name of the stream.
        groupname: name of the consumer group.
        r  r.  r  rB   rB   rC   xinfo_consumers  r  zRedis.xinfo_consumersc                 C   r1  )zx
        Returns general information about the consumer groups of the stream.
        name: name of the stream.
        r  r.  rp  rB   rB   rC   xinfo_groups  r  zRedis.xinfo_groupsc                 C   r1  )za
        Returns general information about the stream.
        name: name of the stream.
        r  r.  rp  rB   rB   rC   xinfo_stream  r  zRedis.xinfo_streamc                 C   r1  )zC
        Returns the number of elements in a given stream.
        XLENr.  rp  rB   rB   rC   xlen  r  z
Redis.xlenc                 C   r}  )z
        Returns information about pending messages of a group.
        name: name of the stream.
        groupname: name of the consumer group.
        r  r.  r  rB   rB   rC   xpending#  r  zRedis.xpendingr   r   c                 C   s   ||g}|dus|dus|dur7|du s|du s|du r t dt|tr)|dk r-t d|||t|f |durP|du sG|du sG|du rKt d|| | jdg|R ddi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. r   z&XPENDING count must be a integer >= -1zaif XPENDING is provided with consumername, it must be provided with min, max and count parametersr  r   T)r   r:   rE   r@   r<   r   r*  )rV   r   r  r   r   r:  r  r/  rB   rB   rC   xpending_range+  s    
zRedis.xpending_ranger  +c                 C   V   ||g}|dur!t |tr|dk rtd|d |t| | jd|g|R  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.
        Nr   z'XRANGE count must be a positive integerr  XRANGEr:   rE   r   r   r<   r*  )rV   r   r   r   r:  r/  rB   rB   rC   xrangeQ     
zRedis.xrangestreamsblockc                 C   s   g }|durt |tr|dk rtd|d |t| |dur<t |tr,|dk r0td|d |t| t |trGt|dkrKtd|d	 t|  \}}|	| |	| | j
d
g|R  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.
        Nr   z*XREAD block must be a non-negative integer   BLOCKr   z&XREAD count must be a positive integerr  z&XREAD streams must be a non empty dict   STREAMSXREAD)r:   rE   r   r   r<   rL   r  r   rT   r@   r*  )rV   r  r:  r  r/  r5   r   rB   rB   rC   xreadk  s$   




zRedis.xreadnoackc                 C   s   d||g}|dur"t |tr|dk rtd|d |t| |dur?t |tr/|dk r3td|d |t| |rF|d	 t |trQt|dkrUtd
|d ||  ||	  | j
dg|R  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
        s   GROUPNr   z+XREADGROUP count must be a positive integerr  r   z/XREADGROUP block must be a non-negative integerr  s   NOACKz+XREADGROUP streams must be a non empty dictr  
XREADGROUP)r:   rE   r   r   r<   rL   r  r@   r5   r   r*  )rV   r  r  r  r:  r  r  r/  rB   rB   rC   
xreadgroup  s&   




zRedis.xreadgroupc                 C   r  )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.
        Nr   z*XREVRANGE count must be a positive integerr  	XREVRANGEr  )rV   r   r   r   r:  r/  rB   rB   rC   	xrevrange  r  zRedis.xrevrangec                 C   s2   dg}|r
| d | | | jd|g|R  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
        r  r  XTRIMr  )rV   r   r}  r  r/  rB   rB   rC   xtrim  s
   

zRedis.xtrimchr   c           
      C   s   |st d|r|rt d|rt|dkrt dg }i }|r%|d |r,|d |r3|d |r>|d d	|d
< | D ]}	||	d  ||	d  qB| jd|g|R i |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 bothr   zFZADD option 'incr' only works when passing a single element/score pairs   NXs   XXs   CHs   INCRTr  r   r  )r   r  r   rT   r*  )
rV   r   r	  r1  r2  r  r   r/  r   r  rB   rB   rC   zadd  s.    



z
Redis.zaddc                 C   r1  )z8Return the number of elements in the sorted set ``name``ZCARDr.  rp  rB   rB   rC   zcard  r4  zRedis.zcardc                 C   r  )z
        Returns the number of elements in the sorted set at key ``name`` with
        a score between ``min`` and ``max``.
        ZCOUNTr.  rV   r   r   r   rB   rB   rC   zcount  r  zRedis.zcountc                 C   r  )zEIncrement the score of ``value`` in sorted set ``name`` by ``amount``ZINCRBYr.  )rV   r   r  r   rB   rB   rC   zincrby   r  zRedis.zincrby	aggregatec                 C   r  )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.
        ZINTERSTORE_zaggregaterV   r  r5   r  rB   rB   rC   zinterstore$  rB  zRedis.zinterstorec                 C   r  )z
        Return the number of items in the sorted set ``name`` between the
        lexicographical range ``min`` and ``max``.
        	ZLEXCOUNTr.  r  rB   rB   rC   	zlexcount1  r  zRedis.zlexcountc                 C   4   |dur|gpg }ddi}| j d|g|R i |S )zy
        Remove and return up to ``count`` members with the highest scores
        from the sorted set ``name``.
        Nr   TZPOPMAXr.  rV   r   r:  r6   r   rB   rB   rC   zpopmax8     zRedis.zpopmaxc                 C   r
  )zx
        Remove and return up to ``count`` members with the lowest scores
        from the sorted set ``name``.
        Nr   TZPOPMINr.  r  rB   rB   rC   zpopminA  r  zRedis.zpopminc                 C   s   t ||f}| jdg|R  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.
        BZPOPMAXr  )rV   r5   r  parsed_keysrB   rB   rC   bzpopmaxJ  s   zRedis.bzpopmaxc                 C   s&   t |d}|| | jdg|R  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.
        NBZPOPMIN)rD   r   r*  )rV   r5   r  klistrB   rB   rC   bzpopminX  s   

zRedis.bzpopminr   c           	      C   sJ   |r|  |||||S d|||g}|r|d ||d}| j|i |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
        ZRANGE
   WITHSCORESr   r   )	zrevranger   r*  )	rV   r   r  r  r  r   r   r/  r   rB   rB   rC   zrangeg  s   

zRedis.zrangec                 C   ^   |dur|du s|dur|du rt dd|||g}|dur*|dur*|d||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.
        Nr  ZRANGEBYLEXr  r   r@   r*  )rV   r   r   r   r  r  r/  rB   rB   rC   zrangebylex      
zRedis.zrangebylexc                 C   r  )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.
        Nr  ZREVRANGEBYLEXr  r  )rV   r   r   r   r  r  r/  rB   rB   rC   zrevrangebylex  r   zRedis.zrevrangebylexc           
      C   |   |dur|du s|dur|du rt dd|||g}|dur*|dur*|d||g |r1|d ||d}	| j|i |	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
        Nr  ZRANGEBYSCOREr  r  r  r   r@   r   r*  
rV   r   r   r   r  r  r   r   r/  r   rB   rB   rC   zrangebyscore      

zRedis.zrangebyscorec                 C   r}  )zi
        Returns a 0-based value indicating the rank of ``value`` in sorted set
        ``name``
        ZRANKr.  r~  rB   rB   rC   zrank  r  zRedis.zrankc                 G   rd  )z1Remove member ``values`` from sorted set ``name``ZREMr.  rf  rB   rB   rC   zrem  rh  z
Redis.zremc                 C   r  )z
        Remove all elements in the sorted set ``name`` between the
        lexicographical range specified by ``min`` and ``max``.

        Returns the number of elements removed.
        ZREMRANGEBYLEXr.  r  rB   rB   rC   zremrangebylex  r  zRedis.zremrangebylexc                 C   r  )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
        ZREMRANGEBYRANKr.  r  rB   rB   rC   zremrangebyrank  r  zRedis.zremrangebyrankc                 C   r  )z
        Remove all elements in the sorted set ``name`` with scores
        between ``min`` and ``max``. Returns the number of elements removed.
        ZREMRANGEBYSCOREr.  r  rB   rB   rC   zremrangebyscore  r  zRedis.zremrangebyscorec                 C   s4   d|||g}|r| d ||d}| j|i |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
        	ZREVRANGEr  r  r  )rV   r   r  r  r   r   r/  r   rB   rB   rC   r    s
   

zRedis.zrevrangec           
      C   r#  )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
        Nr  ZREVRANGEBYSCOREr  r  r  r%  r&  rB   rB   rC   zrevrangebyscore  r(  zRedis.zrevrangebyscorec                 C   r}  )zt
        Returns a 0-based value indicating the descending rank of
        ``value`` in sorted set ``name``
        ZREVRANKr.  r~  rB   rB   rC   zrevrank0  r  zRedis.zrevrankc                 C   r}  )z<Return the score of element ``value`` in sorted set ``name``ZSCOREr.  r~  rB   rB   rC   zscore7  r  zRedis.zscorec                 C   r  )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.
        ZUNIONSTOREr  r  rB   rB   rC   zunionstore;  rB  zRedis.zunionstorec                 C   sx   ||t |g}t|tr| | }}n|}d }|| |r+|d || |r7|d || | j| S )Ns   WEIGHTSs	   AGGREGATE)r  r:   r
   r5   r   r@   r   r*  )rV   r  r  r5   r  r/  	key_namesweightsrB   rB   rC   r  H  s   






zRedis._zaggregatec                 G   rd  )z9Adds the specified elements to the specified HyperLogLog.PFADDr.  rf  rB   rB   rC   pfadda  rh  zRedis.pfaddsourcesc                 G   r  )zo
        Return the approximated cardinality of
        the set observed by the HyperLogLog at key(s).
        PFCOUNTr.  )rV   r@  rB   rB   rC   pfcounte  rJ  zRedis.pfcountc                 G   rd  )z1Merge N different HyperLogLogs into a single one.PFMERGEr.  )rV   r  r@  rB   rB   rC   pfmergel  rh  zRedis.pfmergec                 G   rd  )z"Delete ``keys`` from hash ``name``HDELr.  )rV   r   r5   rB   rB   rC   hdelq  rh  z
Redis.hdelc                 C   r}  )zCReturns a boolean indicating if ``key`` exists within hash ``name``HEXISTSr.  rV   r   r   rB   rB   rC   hexistsu  r  zRedis.hexistsc                 C   r}  )z4Return the value of ``key`` within the hash ``name``HGETr.  rH  rB   rB   rC   hgety  r  z
Redis.hgetc                 C   r1  )z3Return a Python dict of the hash's name/value pairsr  r.  rp  rB   rB   rC   hgetall}  r4  zRedis.hgetallc                 C   r  )z=Increment the value of ``key`` in hash ``name`` by ``amount``HINCRBYr.  rV   r   r   r  rB   rB   rC   hincrby  r  zRedis.hincrbyc                 C   r  )zX
        Increment the value of ``key`` in hash ``name`` by floating ``amount``
        HINCRBYFLOATr.  rN  rB   rB   rC   hincrbyfloat  s   zRedis.hincrbyfloatc                 C   r1  )z,Return the list of keys within hash ``name``HKEYSr.  rp  rB   rB   rC   hkeys  r4  zRedis.hkeysc                 C   r1  )z.Return the number of elements in hash ``name``HLENr.  rp  rB   rB   rC   hlen  r4  z
Redis.hlenc                 C   s^   |du r
|s
t dg }|dur|||f |r%| D ]}|| q| jd|g|R  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 pairsHSET)r   r@   rT   r*  )rV   r   r   r   r	  rT   r  rB   rB   rC   hset  s   z
Redis.hsetc                 C   r  )z
        Set ``key`` to ``value`` within hash ``name`` if ``key`` does not
        exist.  Returns 1 if HSETNX created a field, otherwise 0.
        HSETNXr.  )rV   r   r   r   rB   rB   rC   hsetnx  r  zRedis.hsetnxc                 C   s`   t j| jj d| jj dtdd |stdg }| D ]}|| q| jd|g|R  S )z
        Set key to value within hash ``name`` for each corresponding
        key and value from the ``mapping`` dict.
        z.hmset() is deprecated. Use z.hset() instead.r   )
stacklevelz"'hmset' with 'mapping' of length 0HMSET)	warningsr  r`   ri   DeprecationWarningr   rT   r@   r*  )rV   r   r	  rT   r  rB   rB   rC   hmset  s   
zRedis.hmsetc                 G   r  )z8Returns a list of values ordered identically to ``keys``HMGETr  )rV   r   r5   r6   r  rB   rB   rC   hmget  s   
zRedis.hmgetc                 C   r1  )z.Return the list of values within hash ``name``HVALSr.  rp  rB   rB   rC   hvals  r4  zRedis.hvalsc                 C   r}  )zh
        Return the number of bytes stored in the value of ``key``
        within hash ``name``
        HSTRLENr.  rH  rB   rB   rC   hstrlen  r  zRedis.hstrlenchannelr  c                 C   r}  )z}
        Publish ``message`` on ``channel``.
        Returns the number of subscribers the message was delivered to.
        PUBLISHr.  )rV   re  r  rB   rB   rC   publish  r  zRedis.publishc                 C   r1  )zM
        Return a list of channels that have at least one subscriber
        zPUBSUB CHANNELSr.  r{  rB   rB   rC   pubsub_channels  r  zRedis.pubsub_channelsc                 C   r5  )zA
        Returns the number of subscriptions to patterns
        zPUBSUB NUMPATr.  r  rB   rB   rC   pubsub_numpat  s   
zRedis.pubsub_numpatc                 G   r  )zv
        Return a list of (channel, number of subscribers) tuples
        for each channel given in ``*args``
        r  r.  r<  rB   rB   rC   pubsub_numsub  rJ  zRedis.pubsub_numsubcluster_argc                 G   s   | j d|  g|R  S )NzCLUSTER )r*  rU   )rV   rk  r6   rB   rB   rC   cluster  r   zRedis.clusterscriptnumkeyskeys_and_argsc                 G   r  )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.
        EVALr.  )rV   rm  rn  ro  rB   rB   rC   eval  s   z
Redis.evalshac                 G   r  )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.
        EVALSHAr.  )rV   rr  rn  ro  rB   rB   rC   evalsha  s   
zRedis.evalshac                 G   r  )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.
        r  r.  r<  rB   rB   rC   script_exists
  r  zRedis.script_existsc                 C   r5  )z'Flush all scripts from the script cacher  r.  r  rB   rB   rC   script_flush  r7  zRedis.script_flushc                 C   r5  )z'Kill the currently executing Lua scriptr  r.  r  rB   rB   rC   script_kill  r7  zRedis.script_killc                 C   r1  )z=Load a Lua ``script`` into the script cache. Returns the SHA.r  r.  rV   rm  rB   rB   rC   script_load  r4  zRedis.script_loadScriptc                 C   s
   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.
        )rz  rx  rB   rB   rC   register_script  r?  zRedis.register_scriptc                 G   s,   t |d dkrtd| jd|g|R  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   r   z4GEOADD requires places with lon, lat and name valuesGEOADD)r  r   r*  rf  rB   rB   rC   geoadd(  s   zRedis.geoaddplace1place2unitc                 C   s>   |||g}|r|dvrt d|r|| | jdg|R  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.
        r  kmmiftzGEODIST invalid unitGEODISTr  )rV   r   r~  r  r  r/  rB   rB   rC   geodist3  s   
	
zRedis.geodistc                 G   rd  )z
        Return the geo hash string for each item of ``values`` members of
        the specified key identified by the ``name`` argument.
        r  r.  rf  rB   rB   rC   geohashC  s   zRedis.geohashc                 G   rd  )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  r.  rf  rB   rB   rC   geoposJ  r  zRedis.geopos	longitudelatituderadiusr1  r2  r3  r  r0  c                 C   s$   | j d|||||||||	|
||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  r1  r2  r3  r:  r  r/  r0  _georadiusgeneric)rV   r   r  r  r  r  r1  r2  r3  r:  r  r/  r0  rB   rB   rC   	georadiusR  s   +zRedis.georadiusmemberc                 C   s"   | j d|||||||||	|
|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  )rV   r   r  r  r  r1  r2  r3  r:  r  r/  r0  rB   rB   rC   georadiusbymember  s   zRedis.georadiusbymemberr   c                 O   s$  t |}|d r|d dvrtd|d r||d  n|d dD ]\}}|| r2|| q%|d r@|d|d g |d r`|d d	krP|d
 n|d dkr\|d ntd|d rl|d rltd|d ry|d|d g |d r|d|d g | j|g|R i |S )Nr  r  zGEORADIUS invalid unitr  ))r1  s   WITHDIST)r2  s	   WITHCOORD)r3  s   WITHHASHr:  r  r  ASCs   ASCDESCr  zGEORADIUS invalid sortr/  r0  z3GEORADIUS store and store_dist cant be set togetherr  s	   STOREDIST)r=   r   r   r@   r*  )rV   r  r6   r   r/  arg_name	byte_reprrB   rB   rC   r    s6   
zRedis._georadiusgenericr  c                 C   r1  )zv
        Loads the module from ``path``.
        Raises ``ModuleError`` if a module is not found at ``path``.
        r  r.  )rV   r  rB   rB   rC   module_load  r  zRedis.module_loadc                 C   r1  )zs
        Unloads the module ``name``.
        Raises ``ModuleError`` if ``name`` is not in loaded modules.
        r  r.  rp  rB   rB   rC   module_unload  r  zRedis.module_unloadc                 C   r5  )zo
        Returns a list of dictionaries containing the name and version of
        all loaded modules.
        r  r.  r  rB   rB   rC   module_list  r_  zRedis.module_list)TN)Nr   NNT)r7   r  )r7   r	  )r7   r3   r8   )
FFNNNNNFFF)NNNNF)ry  )FFNFFr   )r   )r  )NNFFF)r   )r   NNN)NNNNFFNF)r   NNN)r   NN)ry  NT)NNNFF)r  F)r  r  N)NNF)r  r  NT)FFFF)NFFFNNNN(L  ri   rj   rk   rl   rQ   r  rE   r   r   r   r  r   r|   r   r   r*   rM  rS  rF  r	  r  r.  r
  rz   rC  r  r   rK   r   rb  r~   rD  r  r   r   r   r   r  r   r   r   r   r  r  r  r   r   r<   r;   ResponseCallbackT__annotations__classmethodr  r   r
   r   rZ   r  r  r2   r  r  r  r   r   r   KeyTr  r   r(   r  r  r  r  r  r  r  r\  r   r  r*  r   r%  r0  r3  r6  r8  r9  r;  r=  r>  r@  r   rX  rY  rZ  r\  r^  ra  rk  rm  rn  ro  rq  rs  rt  rv  rx  r|  r   r  r  r  r  r  r  r  r  r  r   r  KeysTr  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  ExpiryTr  
AbsExpiryTr  rc   r  r  r  r   r  r  PatternTr5   r  r+   r  r  r  r  r  r  r  r   r!  r&  r(  r.  r   r;  rG   r  r=  r?  rA  rD  rG  rI  r)  rA  rN  TimeoutSecTrS  rV  rX  r[  r_  ra  rc  rg  rj  rl  ro  rq  rs  ru  rw  ry  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  GroupT	StreamIdTr  r   FieldTr  	ConsumerTr	   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  ZScoreBoundTr  r  r   r  r	  r  r  r  r  r  r  r"  r'  r*  r,  r.  r0  r2  r  r5  r7  r9  r;  r  r?  rB  rD  rF  rI  rK  rL  rO  rQ  rS  rU  r,   rW  rY  r^  r`  rb  rd  ChannelTrg  rh  ri  rj  rl  ScriptTextTrq  rt  ru  rv  rw  ry  r{  r}  r  r  r  r  r  r  r  r  r  rB   rB   rB   rC   r3     s 
  
 
#&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~     .
	

R

 

?


	


	

 % )"	 	
-&&"" 
	"	  			$   	 
 
"
		"0"&&	" 
""
.	
S 

""$"$""	
'	
G	"	)
&
+(
9($$$$	 	 
#
	 $$		

	  (($((" &
	
@	
#,c                   @   s>   e Zd ZU eed< eed< eed< eed< eed< eed< dS )MonitorCommandInfor  rU  client_addressclient_portclient_typer  N)ri   rj   rk   r   r  rE   r<   rB   rB   rB   rC   r    s   
 r  c                   @   sj   e Zd ZdZedZedZdefddZ	dd Z
d	d
 Zdd ZdefddZdee fddZdS )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"(.*?)(?<!\\)"r  c                 C   s   || _ d | _d S r8   )r  r  )rV   r  rB   rB   rC   rZ     s   
zMonitor.__init__c                    s(   | j d u r| jdI d H | _ d S d S )NMONITOR)r  r  r  r  rB   rB   rC   connect  s   
zMonitor.connectc                    sZ   |   I d H  tt| j| _| jdI d H  | j I d H }t|s+td| | S )Nr  zMONITOR failed: )r  r   r   r  r$  r+  r  r#   rV   rJ   rB   rB   rC   r    s   zMonitor.__aenter__c                    s8   | j d usJ | j  I d H  | j| j I d H  d S r8   )r  r&  r  r!  r<  rB   rB   rC   r    s   zMonitor.__aexit__r7   c                    s
  | j du r
td|  I dH  | j  I dH }t|tr'| j jj|dd}|dd\}}| j	
|}|du r=td| \}}}d| j|}|dd	}|d
kr^d
}d}	d
}
n|drnd}|dd }	d}
n
|dd\}}	d}
t|t|||	|
|dS )z)Parse the response from a monitor commandNzConnection already closed.TrH  r  r   zInvalid command received.z\""luarN  unix   ro   tcp)r  rU  r  r  r  r  )r  r#   r  r+  r:   r;   rN  rM  rN   
monitor_rer  r   r  
command_refindallr  r   r   r   rE   )rV   rJ   command_timecommand_datar  db_idrR  r  r  r  r  rB   rB   rC   next_command  s>   


zMonitor.next_commandc                 C  s   	 |   I dH V  q)z)Listen for commands coming to the server.TN)r  r  rB   rB   rC   listenG  s   zMonitor.listenN)ri   rj   rk   rl   recompiler  r  r   rZ   r  r  r  r  r  r   r  rB   rB   rB   rC   r	    s    


(r	  c                   @   sp  e Zd ZdZdZdZdZ		dEdedee	 d	e
fd
dZdd Zdd Zdd Zdd Zdee fddZdefddZedd ZdefddZdd  ZdFd#e
d$efd%d&Zd'd( Zd)edefd*d+Zded,e fd-d.Z!dedefd/d0Z"ded,e#fd1d2Z$defd3d4Z%de&fd5d6Z'	7dGd	e
d$efd8d9Z(dHdefd:d;Z)dId<d=Z*dd>d?d@edA dBeddfdCdDZ+dS )Jr  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.
    )r  pmessage)unsubscribepunsubscribezaioredis-py-health-checkNFr  r  ignore_subscribe_messagesc                 C   sx   || _ || _|| _d | _| j  | _| jjrd| jg| _n
d| j	| jg| _i | _
t | _i | _t | _t | _d S )Nr*  s   pong)r  r  r  r  rJ  rN  r  HEALTH_CHECK_MESSAGEhealth_check_responserL  channelsr   pending_unsubscribe_channelspatternspending_unsubscribe_patternsr  r(   _lock)rV   r  r  r  rB   rB   rC   rZ   Z  s"   zPubSub.__init__c                       | S r8   rB   r  rB   rB   rC   r  w  rm  zPubSub.__aenter__c                    r  r8   rC  r  rB   rB   rC   r  z  r  zPubSub.__aexit__c                 C   s   | j r
| j   d S d S r8   )r  clear_connect_callbacksr  rB   rB   rC   r   }  s   zPubSub.__del__c              	      s   | j 4 I d H 7 | jr&| j I d H  | j  | j| jI d H  d | _i | _t | _i | _	t | _
W d   I d H  d S 1 I d H sEw   Y  d S r8   )r  r  r&  r  r  r!  r  r   r  r  r  r  rB   rB   rC   rC    s   

.zPubSub.resetr7   c                 C   s   |   S r8   r  r  rB   rB   rC   r    s   zPubSub.closer  c                    s   | j   | j  | jr/i }| j D ]\}}||| jj|dd< q| jdi |I dH  | jrUi }| j D ]\}}||| jj|dd< q9| j	di |I dH  dS dS )zBRe-subscribe to any channels and patterns previously subscribed toTrH  NrB   )
r  clearr  r  rT   rN  rM  	subscriber  
psubscribe)rV   r  r  rX   rY   r  rB   rB   rC   
on_connect  s   

zPubSub.on_connectc                 C   s   t | jp| jS )z@Indicates if there are subscriptions to any channels or patterns)r  r  r  r  rB   rB   rC   
subscribed  s   zPubSub.subscribedr6   c                    sj   | j du r| jd| jI dH | _ | j | j | j }d| j i}| j||jg|R i |I dH  dS )z#Execute a publish/subscribe commandNr  check_health)	r  r  r  r  register_connect_callbackr  r  _executer$  )rV   r6   r  r   rB   rB   rC   r*    s   
&zPubSub.execute_commandc              
      s   z||i |I d H W S  t tfyA } z'| I d H  |jr%t|ts& | I d H  ||i |I d H W  Y d }~S d }~ww r8   )r   r%   r&  r  r:   r  )rV   r  r  r6   r   r)  rB   rB   rC   r    s    zPubSub._executeTr   r  r  c                    sl   | j }|du rtd|  I dH  |s |j|dI dH s dS | ||jI dH }|jr4|| jkr4dS |S )z3Parse the response from a publish/subscribe commandNNpubsub connection not set: did you forget to call subscribe() or psubscribe()?)r  )r  RuntimeErrorr  can_readr  r+  r  r  )rV   r  r  r#  rJ   rB   rB   rC   r%    s   zPubSub.parse_responsec                    sT   | j }|d u rtd|jr&t  |jkr(|jd| jddI d H  d S d S d S )Nr  r  F)r  )	r  r  r  r  r  r  next_health_checkr$  r  r"  rB   rB   rC   r    s   zPubSub.check_healthrW   c                    s(   | j j| j j  fdd| 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.
        c                    s   i | ]\}} ||qS rB   rB   )rq   rX   rY   rM  rL  rB   rC   
<dictcomp>  r   z*PubSub._normalize_keys.<locals>.<dictcomp>)rN  rL  rM  rT   rh   rB   r  rC   _normalize_keys  s   zPubSub._normalize_keysr   c                    sx   |rt |d f|dd n|}t|}|| | jdg| R  I dH }| |}| j| | 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()``.
        r   r   N
PSUBSCRIBE)
rD   rL   rM   rg   r*  r5   r  r  r  difference_update)rV   r6   r   r  new_patternsret_valrB   rB   rC   r        


zPubSub.psubscribec                 G   sZ   |rt |d f|dd }| t| }ng }| j}| j| | jdg|R  S )zj
        Unsubscribe from the supplied patterns. If empty, unsubscribe from
        all patterns.
        r   r   NPUNSUBSCRIBE)	rD   r  rL   rM   r5   r  r  rg   r*  )rV   r6   r  r  rB   rB   rC   r    s   zPubSub.punsubscribec                    sx   |rt |d f|dd nd}t|}|| | jdg| R  I dH }| |}| j| | 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()``.
        r   r   NrB   	SUBSCRIBE)
rD   rL   rM   rg   r*  r5   r  r  r  r  )rV   r6   r   r  new_channelsr  rB   rB   rC   r    r  zPubSub.subscribec                 G   sT   |rt |d |dd }| t|}ng }| j}| j| | jdg|R  S )zi
        Unsubscribe from the supplied channels. If empty, unsubscribe from
        all channels
        r   r   NUNSUBSCRIBE)rD   r  rL   rM   r  r  rg   r*  )rV   r6   r  r  rB   rB   rC   r  /  s   zPubSub.unsubscribec                 C  s<   | j r| | jddI dH }|dur|V  | j sdS dS )zBListen for messages on channels this client has been subscribed toT)r  N)r  handle_messager%  r  rB   rB   rC   r  =  s   zPubSub.listen        c                    s*   | j d|dI dH }|r| ||S dS )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)r  r  N)r%  r  )rV   r  r  rJ   rB   rB   rC   get_messageD  s
   
zPubSub.get_messagec                 C   s   |du rdn|}|  d|S )z'
        Ping the Redis server
        NrN  r  r.  )rV   r  rB   rB   rC   r)  S  s   zPubSub.pingc                 C   s4  t |d }|dkr||d |d |d d}n|dkr&|dd|d d}n|d|d |d d}|| jv rg|d	krQ|d }|| jv rP| j| | j|d n|d }|| jv rg| j| | j|d || jv r|dkrz| j	|d
 d}n	| j	|d d}|r|| dS |S |dkr|s| j
rdS |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.
        r   r  r   r   r   )rA  rz  re  rW   r*  Nr  rz  re  )r*   UNSUBSCRIBE_MESSAGE_TYPESr  remover  popr  r  PUBLISH_MESSAGE_TYPESrc   r  )rV   rJ   r  message_typer  rz  re  handlerrB   rB   rC   r  Z  sR   




zPubSub.handle_messager  )exception_handlerpoll_timeoutr  PSWorkerThreadExcHandlerTr  c             
      s   | j  D ]\}}|du rtd| dq| j D ]\}}|du r,td| dq	 z| jd|dI dH  W n. tjyC     tyh } z|du rO ||| }t	|r^|I dH  W Y d}~nd}~ww t
dI dH  q.)a  Process pub/sub messages using registered callbacks.

        This is the equivalent of :py:meth:`redis.PubSub.run_in_thread` in
        redis-py, but it is a coroutine. To launch it as a separate task, use
        ``asyncio.create_task``:

            >>> task = asyncio.create_task(pubsub.run())

        To shut it down, use asyncio cancellation:

            >>> task.cancel()
            >>> await task
        Nz
Channel: 'z' has no handler registeredz
Pattern: 'T)r  r  r   )r  rT   r"   r  r  r  CancelledErrorBaseExceptionr  r  r  )rV   r  r  re  r  rz  r)  resrB   rB   rC   run  s4   


z
PubSub.runNF)Tr   )Fr  r8   r  ),ri   rj   rk   rl   r  r  r  r   r   r<   r  rZ   r  r  r   rC  r   r   r  r   r  propertyr  r   r*  r  r   r%  r  r4   r  r  PubSubHandlerr  r  r   r  r  r   r  r  r)  r  r  rB   rB   rB   rC   r  M  sb    




>r  c                   @      e Zd ZdedefddZdS )PubsubWorkerExceptionHandlerr)  r  c                 C   re  r8   rB   rV   r)  r  rB   rB   rC   rg    rh  z%PubsubWorkerExceptionHandler.__call__Nri   rj   rk   r  r  rg  rB   rB   rB   rC   r        r  c                   @   r  )!AsyncPubsubWorkerExceptionHandlerr)  r  c                    rl  r8   rB   r  rB   rB   rC   rg    rm  z*AsyncPubsubWorkerExceptionHandler.__call__Nr  rB   rB   rB   rC   r    r   r  .c                	       sj  e Zd ZdZh dZdedeeee	f e
f dedee fddZd	ed
efddZdd Zdd ZdZdd Zdd Zdd Zdd Zdd Zd
ed ed  f fddZdd Zd d! Zd"ed#efd$d%Zd"ed#ed&efd'd(Zd#ed)e e! fd*d+Z"d,e#d-e$d.e e% d
d/fd0d1Z&d"ed2eee	f f fd3d4Z'd5d6 Z(d?d&efd8d9Z)d:e*fd;d<Z+d=d> Z,  Z-S )@r  a_  
    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UNWATCHr  r  r  r  c                 C   s<   || _ d | _|| _|| _|| _d| _g | _t | _d| _	d S r  )
r  r  r  is_transactionr  watchingcommand_stackr   scriptsexplicit_transaction)rV   r  r  r  r  rB   rB   rC   rZ     s   
zPipeline.__init__rV   r7   c                    r  r8   rB   r  rB   rB   rC   r    rm  zPipeline.__aenter__c                    r  r8   r  r  rB   rB   rC   r    r  zPipeline.__aexit__c                 C   r  r8   )_async_selfr  r  rB   rB   rC   r     r   zPipeline.__await__zUnclosed Pipeline clientc                 C   r
  r8   )r  r  r  rB   rB   rC   __len__  r  zPipeline.__len__c                 C   rs  )z1Pipeline instances should always evaluate to TrueTrB   r  rB   rB   rC   __bool__  s   zPipeline.__bool__c                    r  r8   rB   r  rB   rB   rC   r
    rm  zPipeline._async_selfc                    s   g | _ t | _| jr6| jr6z| jdI d H  | j I d H  W n ty5   | jr3| j I d H  Y nw d| _d| _	| jrN| j
| jI d H  d | _d S d S )Nr  F)r  r   r  r  r  r$  r+  r   r&  r	  r  r!  r  rB   rB   rC   rC    s$   
zPipeline.resetc                 C   s&   | j rtd| jrtdd| _ dS )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	  r#   r  r  rB   rB   rC   r^  '  s   
zPipeline.multic                 O   s8   | j s	|d dkr| js| j|i |S | j|i |S )Nr   WATCH)r  r	  immediate_execute_commandpipeline_execute_command)rV   r6   r   rB   rB   rC   r*  4  s   zPipeline.execute_commandc                    sD  |d }| j }|s| j|| jI dH }|| _ tt|}z|j| I dH  | j||fi |I dH W S  tt	fy } zQ|
 I dH  | jrS|  I dH  td||jr[t|t	sc|  I dH   z|j| I dH  | j||fi |W W  Y d}~S  tt	fy   |  I dH   w d}~w tjy   |
 I dH   w )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.
        r   N=A ConnectionError occurred on while watching one or more keys)r  r  r  r  r   r   r$  r%  r   r%   r&  r  rC  r&   r  r:   r  r  )rV   r6   r   r(  r#  r)  rB   rB   rC   r  ;  sH   

"z"Pipeline.immediate_execute_commandc                 O   s   | 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   )rV   r6   r   rB   rB   rC   r  k  s   z!Pipeline.pipeline_execute_commandr  rH  c                    sX  di f}di f}|g||R }| dd |D }||I d H  g }z| |dI d H  W n tyI }	 z|d|	f W Y d }	~	nd }	~	ww t|D ]E\}
}t|d v rd||
|d t f qNz| |dI d H  W qN ty }	 z| |	|
d |d  ||
|	f W Y d }	~	qNd }	~	ww z| |dI d H }W n ty }	 z
|r|d d |	 d }	~	ww d| _	|d u rt
d	d |D ]
\}
}||
| qt|t|kr| jr| j I d H  td
d |r| || g }t||D ]3\}}t|ts$|\}}|d }|| jv r$| j| |fi |}t|r$|I d H }|| q|S )N)MULTI)r  c                 s   s     | ]\}}t |vr|V  qd S r8   )r.   )rq   r6   r   rB   rB   rC   rs     s    
z0Pipeline._execute_transaction.<locals>.<genexpr>r  r   r   FzWatched variable changed.z6Wrong number of response items from pipeline execution)pack_commandssend_packed_commandr%  r$   r   rK  r.   annotate_exceptionr   r  r&   insertr  r  r&  raise_first_errorr   r:   r   r  r  r  )rV   r  rH  raise_on_errorprepostcmdsall_cmdserrorserrr   r  rJ   r)  rW   r   rV  r6   r   r(  rB   rB   rC   _execute_transactionz  sv   


zPipeline._execute_transactionr  c           	         s   | dd |D }||I d H  g }|D ]/\}}z|| j||d fi |I d H  W q tyF } z|| W Y d }~qd }~ww |rO| || |S )Nc                 S   s   g | ]\}}|qS rB   rB   )rq   r6   r  rB   rB   rC   r     r  z.Pipeline._execute_pipeline.<locals>.<listcomp>r   )r  r  r   r%  r$   r  )	rV   r  rH  r  r  rJ   r6   r   r)  rB   rB   rC   _execute_pipeline  s    zPipeline._execute_pipelinerJ   c                 C   s>   t |D ]\}}t|tr| ||d || d  |qd S )Nr   r   )rK  r:   r$   r  )rV   rH  rJ   r   r   rB   rB   rC   r    s   
zPipeline.raise_first_error	exceptionr  r  Nc                 C   sB   d tt|}d| d| d|j }|f|jdd   |_d S )Nr  z
Command # z (z) of pipeline caused error: r   )r  r   r)   r6   )rV   r   r  r  rV  msgrB   rB   rC   r    s   zPipeline.annotate_exceptionr(  c                    s<   t  j||fi |}|| jv rd| _|S |dkrd| _|S )NFr  T)r\   r%  UNWATCH_COMMANDSr  )rV   r  r(  r   r   r_   rB   rC   r%    s   
zPipeline.parse_responsec                    sr   t | j}| j}dd |D }|dg|R  I d H }t|s5t||D ]\}}|s4|d|jI d H |_q$d S d S )Nc                 S   s   g | ]}|j qS rB   )rr  )rq   srB   rB   rC   r     rr  z)Pipeline.load_scripts.<locals>.<listcomp>r  r  )r=   r  r  allr   rm  rr  )rV   r  	immediateshasr  r#  existrB   rB   rC   load_scripts  s   
zPipeline.load_scriptsTc              
      s&  | j }|s| jsg S | jr|  I dH  | js| jr| j}n| j}| j}|s5| j	
d| jI dH }|| _tt|}zPz||||I dH W W |  I dH  S  ttfy } z/| I dH  | jrftd||jrnt|tso ||||I dH W  Y d}~W |  I dH  S d}~ww |  I dH  w )z0Execute all the commands in the current pipelineNr  r  )r  r  r  r(  r  r	  r  r  r  r  r  r  r   r   rC  r   r%   r&  r&   r  r:   )rV   r  stackr  r#  r)  rB   rB   rC   r    s@   

zPipeline.executer  c                    s(   | j rtd| jdg|R  I dH S )z$Watches the values at keys ``names``z"Cannot issue a WATCH after a MULTIr  N)r	  r#   r*  r  rB   rB   rC   r  $  s   zPipeline.watchc                    s   | j r| dI dH pdS )z'Unwatches all previously specified keysr  NT)r  r*  r  rB   rB   rC   unwatch*  s   zPipeline.unwatchr  ).ri   rj   rk   rl   r"  r   r   r   r<   r;   r  r  r   rZ   r2   r  r  r  r  r  r  r
  rC  r^  r   r*  r  r  r   CommandStackTr  r  r   r   r  r   rE   r  r  r%  r(  r  r  r  r*  rm   rB   rB   r_   rC   r    sr    

0
J



(r  c                   @   sT   e Zd ZdZdedefddZ			ddeee	  dee
e  d	ee fd
dZdS )rz  z?An executable Lua script object returned by ``register_script``registered_clientrm  c                 C   sD   || _ || _t|tr|j }||}n|}t|	 | _
d S r8   )r,  rm  r:   r<   r  rJ  rL  hashlibsha1	hexdigestrr  )rV   r,  rm  rN  script_bytesrB   rB   rC   rZ   2  s   

zScript.__init__Nr5   r6   r  c                    s   |pg }|pg }|du r| j }t|t| }t|tr0|j|  |j| jt|g|R  S z|j| jt|g|R  I dH W S  t	yd   |
| jI dH | _|j| jt|g|R  I dH  Y S w )z1Execute the script, passing any required ``args``N)r,  rq  r:   r  r  addrt  rr  r  r!   ry  rm  )rV   r5   r6   r  rB   rB   rC   rg  @  s   
"$zScript.__call__r  )ri   rj   rk   rl   r3   r  rZ   r   r   r  r   r   rg  rB   rB   rB   rC   rz  /  s    

rz  c                
   @   s   e Zd ZdZ	ddededee fddZdd	 Z	d
efddZ
	ddededed
ee fddZdedefddZdededefddZedd Zdd ZdS )r  z0
    Command builder for BITFIELD commands.
    Nr  r   r  c                 C   s*   || _ || _|| _g | _d| _|   d S )NWRAP)r  r   _default_overflow
operations_last_overflowrC  )rV   r  r   r  rB   rB   rC   rZ   `  s   zBitFieldOperation.__init__c                 C   s"   g | _ d| _| | jp| j dS )zL
        Reset the state of the instance to when it was constructed
        r2  N)r4  r5  overflowr3  r  rB   rB   rC   rC  j  s   zBitFieldOperation.resetr6  c                 C   s,   |  }|| jkr|| _| jd|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.
        OVERFLOW)rU   r5  r4  r   )rV   r6  rB   rB   rC   r6  r  s
   
zBitFieldOperation.overflowfmtr  	incrementc                 C   s*   |dur	|  | | jd|||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  )r6  r4  r   )rV   r8  r  r9  r6  rB   rB   rC   r    s   
zBitFieldOperation.incrbyc                 C   s   | j d||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  r4  r   )rV   r8  r  rB   rB   rC   rc     s   
zBitFieldOperation.getr   c                 C   s   | j d|||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:  )rV   r8  r  r   rB   rB   rC   r     s   zBitFieldOperation.setc                 C   s$   d| j g}| jD ]}|| q|S )NBITFIELD)r   r4  r@   )rV   rV  opsrB   rB   rC   r    s   

zBitFieldOperation.commandc                 C   s   | j }|   | jj| 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  rC  r  r*  )rV   r  rB   rB   rC   r    s   zBitFieldOperation.executer8   )ri   rj   rk   rl   r3   r  r   r<   rZ   rC  r6  BitfieldOffsetTrE   r  rc   r   r  r  r  rB   rB   rB   rC   r  [  s6    



r  r  )r  rG   r-  r  r  r  r  r\  typingr   r   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   aioredis.compatr   r   aioredis.connectionr   r   r   r   r   aioredis.exceptionsr   r   r   r    r!   r"   r#   r$   r%   r&   aioredis.lockr(   aioredis.utilsr)   r*   rE   r  r  r  r   r<   r  r=  r;   r?   _StringLikeTr  r  r  r  r  r  r  r  r  r  r+   r,   AnyChannelTr  	SYM_EMPTYr.   r/   r1   r2   r  r4   rD   rK   rQ   rL   rS   rz   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.  rC  rD  rF  rM  rS  rO  rb  rd  rk  r  rn  r3   StrictRedisr  r	  r  r  r  r  CommandTr+  r  rz  r  rB   rB   rB   rC   <module>   sf   X0

,	

                         	O  v$  ],