core.py 233 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670
  1. # from __future__ import annotations
  2. import datetime
  3. import hashlib
  4. import warnings
  5. from typing import (
  6. TYPE_CHECKING,
  7. AsyncIterator,
  8. Awaitable,
  9. Callable,
  10. Dict,
  11. Iterable,
  12. Iterator,
  13. List,
  14. Mapping,
  15. Optional,
  16. Sequence,
  17. Set,
  18. Tuple,
  19. Union,
  20. )
  21. from redis.compat import Literal
  22. from redis.exceptions import ConnectionError, DataError, NoScriptError, RedisError
  23. from redis.typing import (
  24. AbsExpiryT,
  25. AnyKeyT,
  26. BitfieldOffsetT,
  27. ChannelT,
  28. CommandsProtocol,
  29. ConsumerT,
  30. EncodableT,
  31. ExpiryT,
  32. FieldT,
  33. GroupT,
  34. KeysT,
  35. KeyT,
  36. PatternT,
  37. ResponseT,
  38. ScriptTextT,
  39. StreamIdT,
  40. TimeoutSecT,
  41. ZScoreBoundT,
  42. )
  43. from .helpers import list_or_args
  44. if TYPE_CHECKING:
  45. from redis.asyncio.client import Redis as AsyncRedis
  46. from redis.client import Redis
  47. class ACLCommands(CommandsProtocol):
  48. """
  49. Redis Access Control List (ACL) commands.
  50. see: https://redis.io/topics/acl
  51. """
  52. def acl_cat(self, category: Union[str, None] = None, **kwargs) -> ResponseT:
  53. """
  54. Returns a list of categories or commands within a category.
  55. If ``category`` is not supplied, returns a list of all categories.
  56. If ``category`` is supplied, returns a list of all commands within
  57. that category.
  58. For more information see https://redis.io/commands/acl-cat
  59. """
  60. pieces: list[EncodableT] = [category] if category else []
  61. return self.execute_command("ACL CAT", *pieces, **kwargs)
  62. def acl_dryrun(self, username, *args, **kwargs):
  63. """
  64. Simulate the execution of a given command by a given ``username``.
  65. For more information see https://redis.io/commands/acl-dryrun
  66. """
  67. return self.execute_command("ACL DRYRUN", username, *args, **kwargs)
  68. def acl_deluser(self, *username: str, **kwargs) -> ResponseT:
  69. """
  70. Delete the ACL for the specified ``username``s
  71. For more information see https://redis.io/commands/acl-deluser
  72. """
  73. return self.execute_command("ACL DELUSER", *username, **kwargs)
  74. def acl_genpass(self, bits: Union[int, None] = None, **kwargs) -> ResponseT:
  75. """Generate a random password value.
  76. If ``bits`` is supplied then use this number of bits, rounded to
  77. the next multiple of 4.
  78. See: https://redis.io/commands/acl-genpass
  79. """
  80. pieces = []
  81. if bits is not None:
  82. try:
  83. b = int(bits)
  84. if b < 0 or b > 4096:
  85. raise ValueError
  86. pieces.append(b)
  87. except ValueError:
  88. raise DataError(
  89. "genpass optionally accepts a bits argument, between 0 and 4096."
  90. )
  91. return self.execute_command("ACL GENPASS", *pieces, **kwargs)
  92. def acl_getuser(self, username: str, **kwargs) -> ResponseT:
  93. """
  94. Get the ACL details for the specified ``username``.
  95. If ``username`` does not exist, return None
  96. For more information see https://redis.io/commands/acl-getuser
  97. """
  98. return self.execute_command("ACL GETUSER", username, **kwargs)
  99. def acl_help(self, **kwargs) -> ResponseT:
  100. """The ACL HELP command returns helpful text describing
  101. the different subcommands.
  102. For more information see https://redis.io/commands/acl-help
  103. """
  104. return self.execute_command("ACL HELP", **kwargs)
  105. def acl_list(self, **kwargs) -> ResponseT:
  106. """
  107. Return a list of all ACLs on the server
  108. For more information see https://redis.io/commands/acl-list
  109. """
  110. return self.execute_command("ACL LIST", **kwargs)
  111. def acl_log(self, count: Union[int, None] = None, **kwargs) -> ResponseT:
  112. """
  113. Get ACL logs as a list.
  114. :param int count: Get logs[0:count].
  115. :rtype: List.
  116. For more information see https://redis.io/commands/acl-log
  117. """
  118. args = []
  119. if count is not None:
  120. if not isinstance(count, int):
  121. raise DataError("ACL LOG count must be an integer")
  122. args.append(count)
  123. return self.execute_command("ACL LOG", *args, **kwargs)
  124. def acl_log_reset(self, **kwargs) -> ResponseT:
  125. """
  126. Reset ACL logs.
  127. :rtype: Boolean.
  128. For more information see https://redis.io/commands/acl-log
  129. """
  130. args = [b"RESET"]
  131. return self.execute_command("ACL LOG", *args, **kwargs)
  132. def acl_load(self, **kwargs) -> ResponseT:
  133. """
  134. Load ACL rules from the configured ``aclfile``.
  135. Note that the server must be configured with the ``aclfile``
  136. directive to be able to load ACL rules from an aclfile.
  137. For more information see https://redis.io/commands/acl-load
  138. """
  139. return self.execute_command("ACL LOAD", **kwargs)
  140. def acl_save(self, **kwargs) -> ResponseT:
  141. """
  142. Save ACL rules to the configured ``aclfile``.
  143. Note that the server must be configured with the ``aclfile``
  144. directive to be able to save ACL rules to an aclfile.
  145. For more information see https://redis.io/commands/acl-save
  146. """
  147. return self.execute_command("ACL SAVE", **kwargs)
  148. def acl_setuser(
  149. self,
  150. username: str,
  151. enabled: bool = False,
  152. nopass: bool = False,
  153. passwords: Union[str, Iterable[str], None] = None,
  154. hashed_passwords: Union[str, Iterable[str], None] = None,
  155. categories: Optional[Iterable[str]] = None,
  156. commands: Optional[Iterable[str]] = None,
  157. keys: Optional[Iterable[KeyT]] = None,
  158. channels: Optional[Iterable[ChannelT]] = None,
  159. selectors: Optional[Iterable[Tuple[str, KeyT]]] = None,
  160. reset: bool = False,
  161. reset_keys: bool = False,
  162. reset_channels: bool = False,
  163. reset_passwords: bool = False,
  164. **kwargs,
  165. ) -> ResponseT:
  166. """
  167. Create or update an ACL user.
  168. Create or update the ACL for `username`. If the user already exists,
  169. the existing ACL is completely overwritten and replaced with the
  170. specified values.
  171. For more information, see https://redis.io/commands/acl-setuser
  172. Args:
  173. username: The name of the user whose ACL is to be created or updated.
  174. enabled: Indicates whether the user should be allowed to authenticate.
  175. Defaults to `False`.
  176. nopass: Indicates whether the user can authenticate without a password.
  177. This cannot be `True` if `passwords` are also specified.
  178. passwords: A list of plain text passwords to add to or remove from the user.
  179. Each password must be prefixed with a '+' to add or a '-' to
  180. remove. For convenience, a single prefixed string can be used
  181. when adding or removing a single password.
  182. hashed_passwords: A list of SHA-256 hashed passwords to add to or remove
  183. from the user. Each hashed password must be prefixed with
  184. a '+' to add or a '-' to remove. For convenience, a single
  185. prefixed string can be used when adding or removing a
  186. single password.
  187. categories: A list of strings representing category permissions. Each string
  188. must be prefixed with either a '+' to add the category
  189. permission or a '-' to remove the category permission.
  190. commands: A list of strings representing command permissions. Each string
  191. must be prefixed with either a '+' to add the command permission
  192. or a '-' to remove the command permission.
  193. keys: A list of key patterns to grant the user access to. Key patterns allow
  194. '*' to support wildcard matching. For example, '*' grants access to
  195. all keys while 'cache:*' grants access to all keys that are prefixed
  196. with 'cache:'. `keys` should not be prefixed with a '~'.
  197. reset: Indicates whether the user should be fully reset prior to applying
  198. the new ACL. Setting this to `True` will remove all existing
  199. passwords, flags, and privileges from the user and then apply the
  200. specified rules. If `False`, the user's existing passwords, flags,
  201. and privileges will be kept and any new specified rules will be
  202. applied on top.
  203. reset_keys: Indicates whether the user's key permissions should be reset
  204. prior to applying any new key permissions specified in `keys`.
  205. If `False`, the user's existing key permissions will be kept and
  206. any new specified key permissions will be applied on top.
  207. reset_channels: Indicates whether the user's channel permissions should be
  208. reset prior to applying any new channel permissions
  209. specified in `channels`. If `False`, the user's existing
  210. channel permissions will be kept and any new specified
  211. channel permissions will be applied on top.
  212. reset_passwords: Indicates whether to remove all existing passwords and the
  213. `nopass` flag from the user prior to applying any new
  214. passwords specified in `passwords` or `hashed_passwords`.
  215. If `False`, the user's existing passwords and `nopass`
  216. status will be kept and any new specified passwords or
  217. hashed passwords will be applied on top.
  218. """
  219. encoder = self.get_encoder()
  220. pieces: List[EncodableT] = [username]
  221. if reset:
  222. pieces.append(b"reset")
  223. if reset_keys:
  224. pieces.append(b"resetkeys")
  225. if reset_channels:
  226. pieces.append(b"resetchannels")
  227. if reset_passwords:
  228. pieces.append(b"resetpass")
  229. if enabled:
  230. pieces.append(b"on")
  231. else:
  232. pieces.append(b"off")
  233. if (passwords or hashed_passwords) and nopass:
  234. raise DataError(
  235. "Cannot set 'nopass' and supply 'passwords' or 'hashed_passwords'"
  236. )
  237. if passwords:
  238. # as most users will have only one password, allow remove_passwords
  239. # to be specified as a simple string or a list
  240. passwords = list_or_args(passwords, [])
  241. for i, password in enumerate(passwords):
  242. password = encoder.encode(password)
  243. if password.startswith(b"+"):
  244. pieces.append(b">%s" % password[1:])
  245. elif password.startswith(b"-"):
  246. pieces.append(b"<%s" % password[1:])
  247. else:
  248. raise DataError(
  249. f"Password {i} must be prefixed with a "
  250. f'"+" to add or a "-" to remove'
  251. )
  252. if hashed_passwords:
  253. # as most users will have only one password, allow remove_passwords
  254. # to be specified as a simple string or a list
  255. hashed_passwords = list_or_args(hashed_passwords, [])
  256. for i, hashed_password in enumerate(hashed_passwords):
  257. hashed_password = encoder.encode(hashed_password)
  258. if hashed_password.startswith(b"+"):
  259. pieces.append(b"#%s" % hashed_password[1:])
  260. elif hashed_password.startswith(b"-"):
  261. pieces.append(b"!%s" % hashed_password[1:])
  262. else:
  263. raise DataError(
  264. f"Hashed password {i} must be prefixed with a "
  265. f'"+" to add or a "-" to remove'
  266. )
  267. if nopass:
  268. pieces.append(b"nopass")
  269. if categories:
  270. for category in categories:
  271. category = encoder.encode(category)
  272. # categories can be prefixed with one of (+@, +, -@, -)
  273. if category.startswith(b"+@"):
  274. pieces.append(category)
  275. elif category.startswith(b"+"):
  276. pieces.append(b"+@%s" % category[1:])
  277. elif category.startswith(b"-@"):
  278. pieces.append(category)
  279. elif category.startswith(b"-"):
  280. pieces.append(b"-@%s" % category[1:])
  281. else:
  282. raise DataError(
  283. f'Category "{encoder.decode(category, force=True)}" '
  284. 'must be prefixed with "+" or "-"'
  285. )
  286. if commands:
  287. for cmd in commands:
  288. cmd = encoder.encode(cmd)
  289. if not cmd.startswith(b"+") and not cmd.startswith(b"-"):
  290. raise DataError(
  291. f'Command "{encoder.decode(cmd, force=True)}" '
  292. 'must be prefixed with "+" or "-"'
  293. )
  294. pieces.append(cmd)
  295. if keys:
  296. for key in keys:
  297. key = encoder.encode(key)
  298. if not key.startswith(b"%") and not key.startswith(b"~"):
  299. key = b"~%s" % key
  300. pieces.append(key)
  301. if channels:
  302. for channel in channels:
  303. channel = encoder.encode(channel)
  304. pieces.append(b"&%s" % channel)
  305. if selectors:
  306. for cmd, key in selectors:
  307. cmd = encoder.encode(cmd)
  308. if not cmd.startswith(b"+") and not cmd.startswith(b"-"):
  309. raise DataError(
  310. f'Command "{encoder.decode(cmd, force=True)}" '
  311. 'must be prefixed with "+" or "-"'
  312. )
  313. key = encoder.encode(key)
  314. if not key.startswith(b"%") and not key.startswith(b"~"):
  315. key = b"~%s" % key
  316. pieces.append(b"(%s %s)" % (cmd, key))
  317. return self.execute_command("ACL SETUSER", *pieces, **kwargs)
  318. def acl_users(self, **kwargs) -> ResponseT:
  319. """Returns a list of all registered users on the server.
  320. For more information see https://redis.io/commands/acl-users
  321. """
  322. return self.execute_command("ACL USERS", **kwargs)
  323. def acl_whoami(self, **kwargs) -> ResponseT:
  324. """Get the username for the current connection
  325. For more information see https://redis.io/commands/acl-whoami
  326. """
  327. return self.execute_command("ACL WHOAMI", **kwargs)
  328. AsyncACLCommands = ACLCommands
  329. class ManagementCommands(CommandsProtocol):
  330. """
  331. Redis management commands
  332. """
  333. def auth(self, password: str, username: Optional[str] = None, **kwargs):
  334. """
  335. Authenticates the user. If you do not pass username, Redis will try to
  336. authenticate for the "default" user. If you do pass username, it will
  337. authenticate for the given user.
  338. For more information see https://redis.io/commands/auth
  339. """
  340. pieces = []
  341. if username is not None:
  342. pieces.append(username)
  343. pieces.append(password)
  344. return self.execute_command("AUTH", *pieces, **kwargs)
  345. def bgrewriteaof(self, **kwargs):
  346. """Tell the Redis server to rewrite the AOF file from data in memory.
  347. For more information see https://redis.io/commands/bgrewriteaof
  348. """
  349. return self.execute_command("BGREWRITEAOF", **kwargs)
  350. def bgsave(self, schedule: bool = True, **kwargs) -> ResponseT:
  351. """
  352. Tell the Redis server to save its data to disk. Unlike save(),
  353. this method is asynchronous and returns immediately.
  354. For more information see https://redis.io/commands/bgsave
  355. """
  356. pieces = []
  357. if schedule:
  358. pieces.append("SCHEDULE")
  359. return self.execute_command("BGSAVE", *pieces, **kwargs)
  360. def role(self) -> ResponseT:
  361. """
  362. Provide information on the role of a Redis instance in
  363. the context of replication, by returning if the instance
  364. is currently a master, slave, or sentinel.
  365. For more information see https://redis.io/commands/role
  366. """
  367. return self.execute_command("ROLE")
  368. def client_kill(self, address: str, **kwargs) -> ResponseT:
  369. """Disconnects the client at ``address`` (ip:port)
  370. For more information see https://redis.io/commands/client-kill
  371. """
  372. return self.execute_command("CLIENT KILL", address, **kwargs)
  373. def client_kill_filter(
  374. self,
  375. _id: Union[str, None] = None,
  376. _type: Union[str, None] = None,
  377. addr: Union[str, None] = None,
  378. skipme: Union[bool, None] = None,
  379. laddr: Union[bool, None] = None,
  380. user: str = None,
  381. maxage: Union[int, None] = None,
  382. **kwargs,
  383. ) -> ResponseT:
  384. """
  385. Disconnects client(s) using a variety of filter options
  386. :param _id: Kills a client by its unique ID field
  387. :param _type: Kills a client by type where type is one of 'normal',
  388. 'master', 'slave' or 'pubsub'
  389. :param addr: Kills a client by its 'address:port'
  390. :param skipme: If True, then the client calling the command
  391. will not get killed even if it is identified by one of the filter
  392. options. If skipme is not provided, the server defaults to skipme=True
  393. :param laddr: Kills a client by its 'local (bind) address:port'
  394. :param user: Kills a client for a specific user name
  395. :param maxage: Kills clients that are older than the specified age in seconds
  396. """
  397. args = []
  398. if _type is not None:
  399. client_types = ("normal", "master", "slave", "pubsub")
  400. if str(_type).lower() not in client_types:
  401. raise DataError(f"CLIENT KILL type must be one of {client_types!r}")
  402. args.extend((b"TYPE", _type))
  403. if skipme is not None:
  404. if not isinstance(skipme, bool):
  405. raise DataError("CLIENT KILL skipme must be a bool")
  406. if skipme:
  407. args.extend((b"SKIPME", b"YES"))
  408. else:
  409. args.extend((b"SKIPME", b"NO"))
  410. if _id is not None:
  411. args.extend((b"ID", _id))
  412. if addr is not None:
  413. args.extend((b"ADDR", addr))
  414. if laddr is not None:
  415. args.extend((b"LADDR", laddr))
  416. if user is not None:
  417. args.extend((b"USER", user))
  418. if maxage is not None:
  419. args.extend((b"MAXAGE", maxage))
  420. if not args:
  421. raise DataError(
  422. "CLIENT KILL <filter> <value> ... ... <filter> "
  423. "<value> must specify at least one filter"
  424. )
  425. return self.execute_command("CLIENT KILL", *args, **kwargs)
  426. def client_info(self, **kwargs) -> ResponseT:
  427. """
  428. Returns information and statistics about the current
  429. client connection.
  430. For more information see https://redis.io/commands/client-info
  431. """
  432. return self.execute_command("CLIENT INFO", **kwargs)
  433. def client_list(
  434. self, _type: Union[str, None] = None, client_id: List[EncodableT] = [], **kwargs
  435. ) -> ResponseT:
  436. """
  437. Returns a list of currently connected clients.
  438. If type of client specified, only that type will be returned.
  439. :param _type: optional. one of the client types (normal, master,
  440. replica, pubsub)
  441. :param client_id: optional. a list of client ids
  442. For more information see https://redis.io/commands/client-list
  443. """
  444. args = []
  445. if _type is not None:
  446. client_types = ("normal", "master", "replica", "pubsub")
  447. if str(_type).lower() not in client_types:
  448. raise DataError(f"CLIENT LIST _type must be one of {client_types!r}")
  449. args.append(b"TYPE")
  450. args.append(_type)
  451. if not isinstance(client_id, list):
  452. raise DataError("client_id must be a list")
  453. if client_id:
  454. args.append(b"ID")
  455. args.append(" ".join(client_id))
  456. return self.execute_command("CLIENT LIST", *args, **kwargs)
  457. def client_getname(self, **kwargs) -> ResponseT:
  458. """
  459. Returns the current connection name
  460. For more information see https://redis.io/commands/client-getname
  461. """
  462. return self.execute_command("CLIENT GETNAME", **kwargs)
  463. def client_getredir(self, **kwargs) -> ResponseT:
  464. """
  465. Returns the ID (an integer) of the client to whom we are
  466. redirecting tracking notifications.
  467. see: https://redis.io/commands/client-getredir
  468. """
  469. return self.execute_command("CLIENT GETREDIR", **kwargs)
  470. def client_reply(
  471. self, reply: Union[Literal["ON"], Literal["OFF"], Literal["SKIP"]], **kwargs
  472. ) -> ResponseT:
  473. """
  474. Enable and disable redis server replies.
  475. ``reply`` Must be ON OFF or SKIP,
  476. ON - The default most with server replies to commands
  477. OFF - Disable server responses to commands
  478. SKIP - Skip the response of the immediately following command.
  479. Note: When setting OFF or SKIP replies, you will need a client object
  480. with a timeout specified in seconds, and will need to catch the
  481. TimeoutError.
  482. The test_client_reply unit test illustrates this, and
  483. conftest.py has a client with a timeout.
  484. See https://redis.io/commands/client-reply
  485. """
  486. replies = ["ON", "OFF", "SKIP"]
  487. if reply not in replies:
  488. raise DataError(f"CLIENT REPLY must be one of {replies!r}")
  489. return self.execute_command("CLIENT REPLY", reply, **kwargs)
  490. def client_id(self, **kwargs) -> ResponseT:
  491. """
  492. Returns the current connection id
  493. For more information see https://redis.io/commands/client-id
  494. """
  495. return self.execute_command("CLIENT ID", **kwargs)
  496. def client_tracking_on(
  497. self,
  498. clientid: Union[int, None] = None,
  499. prefix: Sequence[KeyT] = [],
  500. bcast: bool = False,
  501. optin: bool = False,
  502. optout: bool = False,
  503. noloop: bool = False,
  504. ) -> ResponseT:
  505. """
  506. Turn on the tracking mode.
  507. For more information about the options look at client_tracking func.
  508. See https://redis.io/commands/client-tracking
  509. """
  510. return self.client_tracking(
  511. True, clientid, prefix, bcast, optin, optout, noloop
  512. )
  513. def client_tracking_off(
  514. self,
  515. clientid: Union[int, None] = None,
  516. prefix: Sequence[KeyT] = [],
  517. bcast: bool = False,
  518. optin: bool = False,
  519. optout: bool = False,
  520. noloop: bool = False,
  521. ) -> ResponseT:
  522. """
  523. Turn off the tracking mode.
  524. For more information about the options look at client_tracking func.
  525. See https://redis.io/commands/client-tracking
  526. """
  527. return self.client_tracking(
  528. False, clientid, prefix, bcast, optin, optout, noloop
  529. )
  530. def client_tracking(
  531. self,
  532. on: bool = True,
  533. clientid: Union[int, None] = None,
  534. prefix: Sequence[KeyT] = [],
  535. bcast: bool = False,
  536. optin: bool = False,
  537. optout: bool = False,
  538. noloop: bool = False,
  539. **kwargs,
  540. ) -> ResponseT:
  541. """
  542. Enables the tracking feature of the Redis server, that is used
  543. for server assisted client side caching.
  544. ``on`` indicate for tracking on or tracking off. The dafualt is on.
  545. ``clientid`` send invalidation messages to the connection with
  546. the specified ID.
  547. ``bcast`` enable tracking in broadcasting mode. In this mode
  548. invalidation messages are reported for all the prefixes
  549. specified, regardless of the keys requested by the connection.
  550. ``optin`` when broadcasting is NOT active, normally don't track
  551. keys in read only commands, unless they are called immediately
  552. after a CLIENT CACHING yes command.
  553. ``optout`` when broadcasting is NOT active, normally track keys in
  554. read only commands, unless they are called immediately after a
  555. CLIENT CACHING no command.
  556. ``noloop`` don't send notifications about keys modified by this
  557. connection itself.
  558. ``prefix`` for broadcasting, register a given key prefix, so that
  559. notifications will be provided only for keys starting with this string.
  560. See https://redis.io/commands/client-tracking
  561. """
  562. if len(prefix) != 0 and bcast is False:
  563. raise DataError("Prefix can only be used with bcast")
  564. pieces = ["ON"] if on else ["OFF"]
  565. if clientid is not None:
  566. pieces.extend(["REDIRECT", clientid])
  567. for p in prefix:
  568. pieces.extend(["PREFIX", p])
  569. if bcast:
  570. pieces.append("BCAST")
  571. if optin:
  572. pieces.append("OPTIN")
  573. if optout:
  574. pieces.append("OPTOUT")
  575. if noloop:
  576. pieces.append("NOLOOP")
  577. return self.execute_command("CLIENT TRACKING", *pieces)
  578. def client_trackinginfo(self, **kwargs) -> ResponseT:
  579. """
  580. Returns the information about the current client connection's
  581. use of the server assisted client side cache.
  582. See https://redis.io/commands/client-trackinginfo
  583. """
  584. return self.execute_command("CLIENT TRACKINGINFO", **kwargs)
  585. def client_setname(self, name: str, **kwargs) -> ResponseT:
  586. """
  587. Sets the current connection name
  588. For more information see https://redis.io/commands/client-setname
  589. .. note::
  590. This method sets client name only for **current** connection.
  591. If you want to set a common name for all connections managed
  592. by this client, use ``client_name`` constructor argument.
  593. """
  594. return self.execute_command("CLIENT SETNAME", name, **kwargs)
  595. def client_setinfo(self, attr: str, value: str, **kwargs) -> ResponseT:
  596. """
  597. Sets the current connection library name or version
  598. For mor information see https://redis.io/commands/client-setinfo
  599. """
  600. return self.execute_command("CLIENT SETINFO", attr, value, **kwargs)
  601. def client_unblock(
  602. self, client_id: int, error: bool = False, **kwargs
  603. ) -> ResponseT:
  604. """
  605. Unblocks a connection by its client id.
  606. If ``error`` is True, unblocks the client with a special error message.
  607. If ``error`` is False (default), the client is unblocked using the
  608. regular timeout mechanism.
  609. For more information see https://redis.io/commands/client-unblock
  610. """
  611. args = ["CLIENT UNBLOCK", int(client_id)]
  612. if error:
  613. args.append(b"ERROR")
  614. return self.execute_command(*args, **kwargs)
  615. def client_pause(self, timeout: int, all: bool = True, **kwargs) -> ResponseT:
  616. """
  617. Suspend all the Redis clients for the specified amount of time.
  618. For more information see https://redis.io/commands/client-pause
  619. :param timeout: milliseconds to pause clients
  620. :param all: If true (default) all client commands are blocked.
  621. otherwise, clients are only blocked if they attempt to execute
  622. a write command.
  623. For the WRITE mode, some commands have special behavior:
  624. EVAL/EVALSHA: Will block client for all scripts.
  625. PUBLISH: Will block client.
  626. PFCOUNT: Will block client.
  627. WAIT: Acknowledgments will be delayed, so this command will
  628. appear blocked.
  629. """
  630. args = ["CLIENT PAUSE", str(timeout)]
  631. if not isinstance(timeout, int):
  632. raise DataError("CLIENT PAUSE timeout must be an integer")
  633. if not all:
  634. args.append("WRITE")
  635. return self.execute_command(*args, **kwargs)
  636. def client_unpause(self, **kwargs) -> ResponseT:
  637. """
  638. Unpause all redis clients
  639. For more information see https://redis.io/commands/client-unpause
  640. """
  641. return self.execute_command("CLIENT UNPAUSE", **kwargs)
  642. def client_no_evict(self, mode: str) -> Union[Awaitable[str], str]:
  643. """
  644. Sets the client eviction mode for the current connection.
  645. For more information see https://redis.io/commands/client-no-evict
  646. """
  647. return self.execute_command("CLIENT NO-EVICT", mode)
  648. def client_no_touch(self, mode: str) -> Union[Awaitable[str], str]:
  649. """
  650. # The command controls whether commands sent by the client will alter
  651. # the LRU/LFU of the keys they access.
  652. # When turned on, the current client will not change LFU/LRU stats,
  653. # unless it sends the TOUCH command.
  654. For more information see https://redis.io/commands/client-no-touch
  655. """
  656. return self.execute_command("CLIENT NO-TOUCH", mode)
  657. def command(self, **kwargs):
  658. """
  659. Returns dict reply of details about all Redis commands.
  660. For more information see https://redis.io/commands/command
  661. """
  662. return self.execute_command("COMMAND", **kwargs)
  663. def command_info(self, **kwargs) -> None:
  664. raise NotImplementedError(
  665. "COMMAND INFO is intentionally not implemented in the client."
  666. )
  667. def command_count(self, **kwargs) -> ResponseT:
  668. return self.execute_command("COMMAND COUNT", **kwargs)
  669. def command_list(
  670. self,
  671. module: Optional[str] = None,
  672. category: Optional[str] = None,
  673. pattern: Optional[str] = None,
  674. ) -> ResponseT:
  675. """
  676. Return an array of the server's command names.
  677. You can use one of the following filters:
  678. ``module``: get the commands that belong to the module
  679. ``category``: get the commands in the ACL category
  680. ``pattern``: get the commands that match the given pattern
  681. For more information see https://redis.io/commands/command-list/
  682. """
  683. pieces = []
  684. if module is not None:
  685. pieces.extend(["MODULE", module])
  686. if category is not None:
  687. pieces.extend(["ACLCAT", category])
  688. if pattern is not None:
  689. pieces.extend(["PATTERN", pattern])
  690. if pieces:
  691. pieces.insert(0, "FILTERBY")
  692. return self.execute_command("COMMAND LIST", *pieces)
  693. def command_getkeysandflags(self, *args: List[str]) -> List[Union[str, List[str]]]:
  694. """
  695. Returns array of keys from a full Redis command and their usage flags.
  696. For more information see https://redis.io/commands/command-getkeysandflags
  697. """
  698. return self.execute_command("COMMAND GETKEYSANDFLAGS", *args)
  699. def command_docs(self, *args):
  700. """
  701. This function throws a NotImplementedError since it is intentionally
  702. not supported.
  703. """
  704. raise NotImplementedError(
  705. "COMMAND DOCS is intentionally not implemented in the client."
  706. )
  707. def config_get(
  708. self, pattern: PatternT = "*", *args: List[PatternT], **kwargs
  709. ) -> ResponseT:
  710. """
  711. Return a dictionary of configuration based on the ``pattern``
  712. For more information see https://redis.io/commands/config-get
  713. """
  714. return self.execute_command("CONFIG GET", pattern, *args, **kwargs)
  715. def config_set(
  716. self,
  717. name: KeyT,
  718. value: EncodableT,
  719. *args: List[Union[KeyT, EncodableT]],
  720. **kwargs,
  721. ) -> ResponseT:
  722. """Set config item ``name`` with ``value``
  723. For more information see https://redis.io/commands/config-set
  724. """
  725. return self.execute_command("CONFIG SET", name, value, *args, **kwargs)
  726. def config_resetstat(self, **kwargs) -> ResponseT:
  727. """
  728. Reset runtime statistics
  729. For more information see https://redis.io/commands/config-resetstat
  730. """
  731. return self.execute_command("CONFIG RESETSTAT", **kwargs)
  732. def config_rewrite(self, **kwargs) -> ResponseT:
  733. """
  734. Rewrite config file with the minimal change to reflect running config.
  735. For more information see https://redis.io/commands/config-rewrite
  736. """
  737. return self.execute_command("CONFIG REWRITE", **kwargs)
  738. def dbsize(self, **kwargs) -> ResponseT:
  739. """
  740. Returns the number of keys in the current database
  741. For more information see https://redis.io/commands/dbsize
  742. """
  743. return self.execute_command("DBSIZE", **kwargs)
  744. def debug_object(self, key: KeyT, **kwargs) -> ResponseT:
  745. """
  746. Returns version specific meta information about a given key
  747. For more information see https://redis.io/commands/debug-object
  748. """
  749. return self.execute_command("DEBUG OBJECT", key, **kwargs)
  750. def debug_segfault(self, **kwargs) -> None:
  751. raise NotImplementedError(
  752. """
  753. DEBUG SEGFAULT is intentionally not implemented in the client.
  754. For more information see https://redis.io/commands/debug-segfault
  755. """
  756. )
  757. def echo(self, value: EncodableT, **kwargs) -> ResponseT:
  758. """
  759. Echo the string back from the server
  760. For more information see https://redis.io/commands/echo
  761. """
  762. return self.execute_command("ECHO", value, **kwargs)
  763. def flushall(self, asynchronous: bool = False, **kwargs) -> ResponseT:
  764. """
  765. Delete all keys in all databases on the current host.
  766. ``asynchronous`` indicates whether the operation is
  767. executed asynchronously by the server.
  768. For more information see https://redis.io/commands/flushall
  769. """
  770. args = []
  771. if asynchronous:
  772. args.append(b"ASYNC")
  773. return self.execute_command("FLUSHALL", *args, **kwargs)
  774. def flushdb(self, asynchronous: bool = False, **kwargs) -> ResponseT:
  775. """
  776. Delete all keys in the current database.
  777. ``asynchronous`` indicates whether the operation is
  778. executed asynchronously by the server.
  779. For more information see https://redis.io/commands/flushdb
  780. """
  781. args = []
  782. if asynchronous:
  783. args.append(b"ASYNC")
  784. return self.execute_command("FLUSHDB", *args, **kwargs)
  785. def sync(self) -> ResponseT:
  786. """
  787. Initiates a replication stream from the master.
  788. For more information see https://redis.io/commands/sync
  789. """
  790. from redis.client import NEVER_DECODE
  791. options = {}
  792. options[NEVER_DECODE] = []
  793. return self.execute_command("SYNC", **options)
  794. def psync(self, replicationid: str, offset: int):
  795. """
  796. Initiates a replication stream from the master.
  797. Newer version for `sync`.
  798. For more information see https://redis.io/commands/sync
  799. """
  800. from redis.client import NEVER_DECODE
  801. options = {}
  802. options[NEVER_DECODE] = []
  803. return self.execute_command("PSYNC", replicationid, offset, **options)
  804. def swapdb(self, first: int, second: int, **kwargs) -> ResponseT:
  805. """
  806. Swap two databases
  807. For more information see https://redis.io/commands/swapdb
  808. """
  809. return self.execute_command("SWAPDB", first, second, **kwargs)
  810. def select(self, index: int, **kwargs) -> ResponseT:
  811. """Select the Redis logical database at index.
  812. See: https://redis.io/commands/select
  813. """
  814. return self.execute_command("SELECT", index, **kwargs)
  815. def info(
  816. self, section: Union[str, None] = None, *args: List[str], **kwargs
  817. ) -> ResponseT:
  818. """
  819. Returns a dictionary containing information about the Redis server
  820. The ``section`` option can be used to select a specific section
  821. of information
  822. The section option is not supported by older versions of Redis Server,
  823. and will generate ResponseError
  824. For more information see https://redis.io/commands/info
  825. """
  826. if section is None:
  827. return self.execute_command("INFO", **kwargs)
  828. else:
  829. return self.execute_command("INFO", section, *args, **kwargs)
  830. def lastsave(self, **kwargs) -> ResponseT:
  831. """
  832. Return a Python datetime object representing the last time the
  833. Redis database was saved to disk
  834. For more information see https://redis.io/commands/lastsave
  835. """
  836. return self.execute_command("LASTSAVE", **kwargs)
  837. def latency_doctor(self):
  838. """Raise a NotImplementedError, as the client will not support LATENCY DOCTOR.
  839. This funcion is best used within the redis-cli.
  840. For more information see https://redis.io/commands/latency-doctor
  841. """
  842. raise NotImplementedError(
  843. """
  844. LATENCY DOCTOR is intentionally not implemented in the client.
  845. For more information see https://redis.io/commands/latency-doctor
  846. """
  847. )
  848. def latency_graph(self):
  849. """Raise a NotImplementedError, as the client will not support LATENCY GRAPH.
  850. This funcion is best used within the redis-cli.
  851. For more information see https://redis.io/commands/latency-graph.
  852. """
  853. raise NotImplementedError(
  854. """
  855. LATENCY GRAPH is intentionally not implemented in the client.
  856. For more information see https://redis.io/commands/latency-graph
  857. """
  858. )
  859. def lolwut(self, *version_numbers: Union[str, float], **kwargs) -> ResponseT:
  860. """
  861. Get the Redis version and a piece of generative computer art
  862. See: https://redis.io/commands/lolwut
  863. """
  864. if version_numbers:
  865. return self.execute_command("LOLWUT VERSION", *version_numbers, **kwargs)
  866. else:
  867. return self.execute_command("LOLWUT", **kwargs)
  868. def reset(self) -> ResponseT:
  869. """Perform a full reset on the connection's server side contenxt.
  870. See: https://redis.io/commands/reset
  871. """
  872. return self.execute_command("RESET")
  873. def migrate(
  874. self,
  875. host: str,
  876. port: int,
  877. keys: KeysT,
  878. destination_db: int,
  879. timeout: int,
  880. copy: bool = False,
  881. replace: bool = False,
  882. auth: Union[str, None] = None,
  883. **kwargs,
  884. ) -> ResponseT:
  885. """
  886. Migrate 1 or more keys from the current Redis server to a different
  887. server specified by the ``host``, ``port`` and ``destination_db``.
  888. The ``timeout``, specified in milliseconds, indicates the maximum
  889. time the connection between the two servers can be idle before the
  890. command is interrupted.
  891. If ``copy`` is True, the specified ``keys`` are NOT deleted from
  892. the source server.
  893. If ``replace`` is True, this operation will overwrite the keys
  894. on the destination server if they exist.
  895. If ``auth`` is specified, authenticate to the destination server with
  896. the password provided.
  897. For more information see https://redis.io/commands/migrate
  898. """
  899. keys = list_or_args(keys, [])
  900. if not keys:
  901. raise DataError("MIGRATE requires at least one key")
  902. pieces = []
  903. if copy:
  904. pieces.append(b"COPY")
  905. if replace:
  906. pieces.append(b"REPLACE")
  907. if auth:
  908. pieces.append(b"AUTH")
  909. pieces.append(auth)
  910. pieces.append(b"KEYS")
  911. pieces.extend(keys)
  912. return self.execute_command(
  913. "MIGRATE", host, port, "", destination_db, timeout, *pieces, **kwargs
  914. )
  915. def object(self, infotype: str, key: KeyT, **kwargs) -> ResponseT:
  916. """
  917. Return the encoding, idletime, or refcount about the key
  918. """
  919. return self.execute_command(
  920. "OBJECT", infotype, key, infotype=infotype, **kwargs
  921. )
  922. def memory_doctor(self, **kwargs) -> None:
  923. raise NotImplementedError(
  924. """
  925. MEMORY DOCTOR is intentionally not implemented in the client.
  926. For more information see https://redis.io/commands/memory-doctor
  927. """
  928. )
  929. def memory_help(self, **kwargs) -> None:
  930. raise NotImplementedError(
  931. """
  932. MEMORY HELP is intentionally not implemented in the client.
  933. For more information see https://redis.io/commands/memory-help
  934. """
  935. )
  936. def memory_stats(self, **kwargs) -> ResponseT:
  937. """
  938. Return a dictionary of memory stats
  939. For more information see https://redis.io/commands/memory-stats
  940. """
  941. return self.execute_command("MEMORY STATS", **kwargs)
  942. def memory_malloc_stats(self, **kwargs) -> ResponseT:
  943. """
  944. Return an internal statistics report from the memory allocator.
  945. See: https://redis.io/commands/memory-malloc-stats
  946. """
  947. return self.execute_command("MEMORY MALLOC-STATS", **kwargs)
  948. def memory_usage(
  949. self, key: KeyT, samples: Union[int, None] = None, **kwargs
  950. ) -> ResponseT:
  951. """
  952. Return the total memory usage for key, its value and associated
  953. administrative overheads.
  954. For nested data structures, ``samples`` is the number of elements to
  955. sample. If left unspecified, the server's default is 5. Use 0 to sample
  956. all elements.
  957. For more information see https://redis.io/commands/memory-usage
  958. """
  959. args = []
  960. if isinstance(samples, int):
  961. args.extend([b"SAMPLES", samples])
  962. return self.execute_command("MEMORY USAGE", key, *args, **kwargs)
  963. def memory_purge(self, **kwargs) -> ResponseT:
  964. """
  965. Attempts to purge dirty pages for reclamation by allocator
  966. For more information see https://redis.io/commands/memory-purge
  967. """
  968. return self.execute_command("MEMORY PURGE", **kwargs)
  969. def latency_histogram(self, *args):
  970. """
  971. This function throws a NotImplementedError since it is intentionally
  972. not supported.
  973. """
  974. raise NotImplementedError(
  975. "LATENCY HISTOGRAM is intentionally not implemented in the client."
  976. )
  977. def latency_history(self, event: str) -> ResponseT:
  978. """
  979. Returns the raw data of the ``event``'s latency spikes time series.
  980. For more information see https://redis.io/commands/latency-history
  981. """
  982. return self.execute_command("LATENCY HISTORY", event)
  983. def latency_latest(self) -> ResponseT:
  984. """
  985. Reports the latest latency events logged.
  986. For more information see https://redis.io/commands/latency-latest
  987. """
  988. return self.execute_command("LATENCY LATEST")
  989. def latency_reset(self, *events: str) -> ResponseT:
  990. """
  991. Resets the latency spikes time series of all, or only some, events.
  992. For more information see https://redis.io/commands/latency-reset
  993. """
  994. return self.execute_command("LATENCY RESET", *events)
  995. def ping(self, **kwargs) -> ResponseT:
  996. """
  997. Ping the Redis server
  998. For more information see https://redis.io/commands/ping
  999. """
  1000. return self.execute_command("PING", **kwargs)
  1001. def quit(self, **kwargs) -> ResponseT:
  1002. """
  1003. Ask the server to close the connection.
  1004. For more information see https://redis.io/commands/quit
  1005. """
  1006. return self.execute_command("QUIT", **kwargs)
  1007. def replicaof(self, *args, **kwargs) -> ResponseT:
  1008. """
  1009. Update the replication settings of a redis replica, on the fly.
  1010. Examples of valid arguments include:
  1011. NO ONE (set no replication)
  1012. host port (set to the host and port of a redis server)
  1013. For more information see https://redis.io/commands/replicaof
  1014. """
  1015. return self.execute_command("REPLICAOF", *args, **kwargs)
  1016. def save(self, **kwargs) -> ResponseT:
  1017. """
  1018. Tell the Redis server to save its data to disk,
  1019. blocking until the save is complete
  1020. For more information see https://redis.io/commands/save
  1021. """
  1022. return self.execute_command("SAVE", **kwargs)
  1023. def shutdown(
  1024. self,
  1025. save: bool = False,
  1026. nosave: bool = False,
  1027. now: bool = False,
  1028. force: bool = False,
  1029. abort: bool = False,
  1030. **kwargs,
  1031. ) -> None:
  1032. """Shutdown the Redis server. If Redis has persistence configured,
  1033. data will be flushed before shutdown.
  1034. It is possible to specify modifiers to alter the behavior of the command:
  1035. ``save`` will force a DB saving operation even if no save points are configured.
  1036. ``nosave`` will prevent a DB saving operation even if one or more save points
  1037. are configured.
  1038. ``now`` skips waiting for lagging replicas, i.e. it bypasses the first step in
  1039. the shutdown sequence.
  1040. ``force`` ignores any errors that would normally prevent the server from exiting
  1041. ``abort`` cancels an ongoing shutdown and cannot be combined with other flags.
  1042. For more information see https://redis.io/commands/shutdown
  1043. """
  1044. if save and nosave:
  1045. raise DataError("SHUTDOWN save and nosave cannot both be set")
  1046. args = ["SHUTDOWN"]
  1047. if save:
  1048. args.append("SAVE")
  1049. if nosave:
  1050. args.append("NOSAVE")
  1051. if now:
  1052. args.append("NOW")
  1053. if force:
  1054. args.append("FORCE")
  1055. if abort:
  1056. args.append("ABORT")
  1057. try:
  1058. self.execute_command(*args, **kwargs)
  1059. except ConnectionError:
  1060. # a ConnectionError here is expected
  1061. return
  1062. raise RedisError("SHUTDOWN seems to have failed.")
  1063. def slaveof(
  1064. self, host: Union[str, None] = None, port: Union[int, None] = None, **kwargs
  1065. ) -> ResponseT:
  1066. """
  1067. Set the server to be a replicated slave of the instance identified
  1068. by the ``host`` and ``port``. If called without arguments, the
  1069. instance is promoted to a master instead.
  1070. For more information see https://redis.io/commands/slaveof
  1071. """
  1072. if host is None and port is None:
  1073. return self.execute_command("SLAVEOF", b"NO", b"ONE", **kwargs)
  1074. return self.execute_command("SLAVEOF", host, port, **kwargs)
  1075. def slowlog_get(self, num: Union[int, None] = None, **kwargs) -> ResponseT:
  1076. """
  1077. Get the entries from the slowlog. If ``num`` is specified, get the
  1078. most recent ``num`` items.
  1079. For more information see https://redis.io/commands/slowlog-get
  1080. """
  1081. from redis.client import NEVER_DECODE
  1082. args = ["SLOWLOG GET"]
  1083. if num is not None:
  1084. args.append(num)
  1085. decode_responses = self.get_connection_kwargs().get("decode_responses", False)
  1086. if decode_responses is True:
  1087. kwargs[NEVER_DECODE] = []
  1088. return self.execute_command(*args, **kwargs)
  1089. def slowlog_len(self, **kwargs) -> ResponseT:
  1090. """
  1091. Get the number of items in the slowlog
  1092. For more information see https://redis.io/commands/slowlog-len
  1093. """
  1094. return self.execute_command("SLOWLOG LEN", **kwargs)
  1095. def slowlog_reset(self, **kwargs) -> ResponseT:
  1096. """
  1097. Remove all items in the slowlog
  1098. For more information see https://redis.io/commands/slowlog-reset
  1099. """
  1100. return self.execute_command("SLOWLOG RESET", **kwargs)
  1101. def time(self, **kwargs) -> ResponseT:
  1102. """
  1103. Returns the server time as a 2-item tuple of ints:
  1104. (seconds since epoch, microseconds into this second).
  1105. For more information see https://redis.io/commands/time
  1106. """
  1107. return self.execute_command("TIME", **kwargs)
  1108. def wait(self, num_replicas: int, timeout: int, **kwargs) -> ResponseT:
  1109. """
  1110. Redis synchronous replication
  1111. That returns the number of replicas that processed the query when
  1112. we finally have at least ``num_replicas``, or when the ``timeout`` was
  1113. reached.
  1114. For more information see https://redis.io/commands/wait
  1115. """
  1116. return self.execute_command("WAIT", num_replicas, timeout, **kwargs)
  1117. def waitaof(
  1118. self, num_local: int, num_replicas: int, timeout: int, **kwargs
  1119. ) -> ResponseT:
  1120. """
  1121. This command blocks the current client until all previous write
  1122. commands by that client are acknowledged as having been fsynced
  1123. to the AOF of the local Redis and/or at least the specified number
  1124. of replicas.
  1125. For more information see https://redis.io/commands/waitaof
  1126. """
  1127. return self.execute_command(
  1128. "WAITAOF", num_local, num_replicas, timeout, **kwargs
  1129. )
  1130. def hello(self):
  1131. """
  1132. This function throws a NotImplementedError since it is intentionally
  1133. not supported.
  1134. """
  1135. raise NotImplementedError(
  1136. "HELLO is intentionally not implemented in the client."
  1137. )
  1138. def failover(self):
  1139. """
  1140. This function throws a NotImplementedError since it is intentionally
  1141. not supported.
  1142. """
  1143. raise NotImplementedError(
  1144. "FAILOVER is intentionally not implemented in the client."
  1145. )
  1146. AsyncManagementCommands = ManagementCommands
  1147. class AsyncManagementCommands(ManagementCommands):
  1148. async def command_info(self, **kwargs) -> None:
  1149. return super().command_info(**kwargs)
  1150. async def debug_segfault(self, **kwargs) -> None:
  1151. return super().debug_segfault(**kwargs)
  1152. async def memory_doctor(self, **kwargs) -> None:
  1153. return super().memory_doctor(**kwargs)
  1154. async def memory_help(self, **kwargs) -> None:
  1155. return super().memory_help(**kwargs)
  1156. async def shutdown(
  1157. self,
  1158. save: bool = False,
  1159. nosave: bool = False,
  1160. now: bool = False,
  1161. force: bool = False,
  1162. abort: bool = False,
  1163. **kwargs,
  1164. ) -> None:
  1165. """Shutdown the Redis server. If Redis has persistence configured,
  1166. data will be flushed before shutdown. If the "save" option is set,
  1167. a data flush will be attempted even if there is no persistence
  1168. configured. If the "nosave" option is set, no data flush will be
  1169. attempted. The "save" and "nosave" options cannot both be set.
  1170. For more information see https://redis.io/commands/shutdown
  1171. """
  1172. if save and nosave:
  1173. raise DataError("SHUTDOWN save and nosave cannot both be set")
  1174. args = ["SHUTDOWN"]
  1175. if save:
  1176. args.append("SAVE")
  1177. if nosave:
  1178. args.append("NOSAVE")
  1179. if now:
  1180. args.append("NOW")
  1181. if force:
  1182. args.append("FORCE")
  1183. if abort:
  1184. args.append("ABORT")
  1185. try:
  1186. await self.execute_command(*args, **kwargs)
  1187. except ConnectionError:
  1188. # a ConnectionError here is expected
  1189. return
  1190. raise RedisError("SHUTDOWN seems to have failed.")
  1191. class BitFieldOperation:
  1192. """
  1193. Command builder for BITFIELD commands.
  1194. """
  1195. def __init__(
  1196. self,
  1197. client: Union["Redis", "AsyncRedis"],
  1198. key: str,
  1199. default_overflow: Union[str, None] = None,
  1200. ):
  1201. self.client = client
  1202. self.key = key
  1203. self._default_overflow = default_overflow
  1204. # for typing purposes, run the following in constructor and in reset()
  1205. self.operations: list[tuple[EncodableT, ...]] = []
  1206. self._last_overflow = "WRAP"
  1207. self.reset()
  1208. def reset(self):
  1209. """
  1210. Reset the state of the instance to when it was constructed
  1211. """
  1212. self.operations = []
  1213. self._last_overflow = "WRAP"
  1214. self.overflow(self._default_overflow or self._last_overflow)
  1215. def overflow(self, overflow: str):
  1216. """
  1217. Update the overflow algorithm of successive INCRBY operations
  1218. :param overflow: Overflow algorithm, one of WRAP, SAT, FAIL. See the
  1219. Redis docs for descriptions of these algorithmsself.
  1220. :returns: a :py:class:`BitFieldOperation` instance.
  1221. """
  1222. overflow = overflow.upper()
  1223. if overflow != self._last_overflow:
  1224. self._last_overflow = overflow
  1225. self.operations.append(("OVERFLOW", overflow))
  1226. return self
  1227. def incrby(
  1228. self,
  1229. fmt: str,
  1230. offset: BitfieldOffsetT,
  1231. increment: int,
  1232. overflow: Union[str, None] = None,
  1233. ):
  1234. """
  1235. Increment a bitfield by a given amount.
  1236. :param fmt: format-string for the bitfield being updated, e.g. 'u8'
  1237. for an unsigned 8-bit integer.
  1238. :param offset: offset (in number of bits). If prefixed with a
  1239. '#', this is an offset multiplier, e.g. given the arguments
  1240. fmt='u8', offset='#2', the offset will be 16.
  1241. :param int increment: value to increment the bitfield by.
  1242. :param str overflow: overflow algorithm. Defaults to WRAP, but other
  1243. acceptable values are SAT and FAIL. See the Redis docs for
  1244. descriptions of these algorithms.
  1245. :returns: a :py:class:`BitFieldOperation` instance.
  1246. """
  1247. if overflow is not None:
  1248. self.overflow(overflow)
  1249. self.operations.append(("INCRBY", fmt, offset, increment))
  1250. return self
  1251. def get(self, fmt: str, offset: BitfieldOffsetT):
  1252. """
  1253. Get the value of a given bitfield.
  1254. :param fmt: format-string for the bitfield being read, e.g. 'u8' for
  1255. an unsigned 8-bit integer.
  1256. :param offset: offset (in number of bits). If prefixed with a
  1257. '#', this is an offset multiplier, e.g. given the arguments
  1258. fmt='u8', offset='#2', the offset will be 16.
  1259. :returns: a :py:class:`BitFieldOperation` instance.
  1260. """
  1261. self.operations.append(("GET", fmt, offset))
  1262. return self
  1263. def set(self, fmt: str, offset: BitfieldOffsetT, value: int):
  1264. """
  1265. Set the value of a given bitfield.
  1266. :param fmt: format-string for the bitfield being read, e.g. 'u8' for
  1267. an unsigned 8-bit integer.
  1268. :param offset: offset (in number of bits). If prefixed with a
  1269. '#', this is an offset multiplier, e.g. given the arguments
  1270. fmt='u8', offset='#2', the offset will be 16.
  1271. :param int value: value to set at the given position.
  1272. :returns: a :py:class:`BitFieldOperation` instance.
  1273. """
  1274. self.operations.append(("SET", fmt, offset, value))
  1275. return self
  1276. @property
  1277. def command(self):
  1278. cmd = ["BITFIELD", self.key]
  1279. for ops in self.operations:
  1280. cmd.extend(ops)
  1281. return cmd
  1282. def execute(self) -> ResponseT:
  1283. """
  1284. Execute the operation(s) in a single BITFIELD command. The return value
  1285. is a list of values corresponding to each operation. If the client
  1286. used to create this instance was a pipeline, the list of values
  1287. will be present within the pipeline's execute.
  1288. """
  1289. command = self.command
  1290. self.reset()
  1291. return self.client.execute_command(*command)
  1292. class BasicKeyCommands(CommandsProtocol):
  1293. """
  1294. Redis basic key-based commands
  1295. """
  1296. def append(self, key: KeyT, value: EncodableT) -> ResponseT:
  1297. """
  1298. Appends the string ``value`` to the value at ``key``. If ``key``
  1299. doesn't already exist, create it with a value of ``value``.
  1300. Returns the new length of the value at ``key``.
  1301. For more information see https://redis.io/commands/append
  1302. """
  1303. return self.execute_command("APPEND", key, value)
  1304. def bitcount(
  1305. self,
  1306. key: KeyT,
  1307. start: Union[int, None] = None,
  1308. end: Union[int, None] = None,
  1309. mode: Optional[str] = None,
  1310. ) -> ResponseT:
  1311. """
  1312. Returns the count of set bits in the value of ``key``. Optional
  1313. ``start`` and ``end`` parameters indicate which bytes to consider
  1314. For more information see https://redis.io/commands/bitcount
  1315. """
  1316. params = [key]
  1317. if start is not None and end is not None:
  1318. params.append(start)
  1319. params.append(end)
  1320. elif (start is not None and end is None) or (end is not None and start is None):
  1321. raise DataError("Both start and end must be specified")
  1322. if mode is not None:
  1323. params.append(mode)
  1324. return self.execute_command("BITCOUNT", *params)
  1325. def bitfield(
  1326. self: Union["Redis", "AsyncRedis"],
  1327. key: KeyT,
  1328. default_overflow: Union[str, None] = None,
  1329. ) -> BitFieldOperation:
  1330. """
  1331. Return a BitFieldOperation instance to conveniently construct one or
  1332. more bitfield operations on ``key``.
  1333. For more information see https://redis.io/commands/bitfield
  1334. """
  1335. return BitFieldOperation(self, key, default_overflow=default_overflow)
  1336. def bitfield_ro(
  1337. self: Union["Redis", "AsyncRedis"],
  1338. key: KeyT,
  1339. encoding: str,
  1340. offset: BitfieldOffsetT,
  1341. items: Optional[list] = None,
  1342. ) -> ResponseT:
  1343. """
  1344. Return an array of the specified bitfield values
  1345. where the first value is found using ``encoding`` and ``offset``
  1346. parameters and remaining values are result of corresponding
  1347. encoding/offset pairs in optional list ``items``
  1348. Read-only variant of the BITFIELD command.
  1349. For more information see https://redis.io/commands/bitfield_ro
  1350. """
  1351. params = [key, "GET", encoding, offset]
  1352. items = items or []
  1353. for encoding, offset in items:
  1354. params.extend(["GET", encoding, offset])
  1355. return self.execute_command("BITFIELD_RO", *params)
  1356. def bitop(self, operation: str, dest: KeyT, *keys: KeyT) -> ResponseT:
  1357. """
  1358. Perform a bitwise operation using ``operation`` between ``keys`` and
  1359. store the result in ``dest``.
  1360. For more information see https://redis.io/commands/bitop
  1361. """
  1362. return self.execute_command("BITOP", operation, dest, *keys)
  1363. def bitpos(
  1364. self,
  1365. key: KeyT,
  1366. bit: int,
  1367. start: Union[int, None] = None,
  1368. end: Union[int, None] = None,
  1369. mode: Optional[str] = None,
  1370. ) -> ResponseT:
  1371. """
  1372. Return the position of the first bit set to 1 or 0 in a string.
  1373. ``start`` and ``end`` defines search range. The range is interpreted
  1374. as a range of bytes and not a range of bits, so start=0 and end=2
  1375. means to look at the first three bytes.
  1376. For more information see https://redis.io/commands/bitpos
  1377. """
  1378. if bit not in (0, 1):
  1379. raise DataError("bit must be 0 or 1")
  1380. params = [key, bit]
  1381. start is not None and params.append(start)
  1382. if start is not None and end is not None:
  1383. params.append(end)
  1384. elif start is None and end is not None:
  1385. raise DataError("start argument is not set, when end is specified")
  1386. if mode is not None:
  1387. params.append(mode)
  1388. return self.execute_command("BITPOS", *params)
  1389. def copy(
  1390. self,
  1391. source: str,
  1392. destination: str,
  1393. destination_db: Union[str, None] = None,
  1394. replace: bool = False,
  1395. ) -> ResponseT:
  1396. """
  1397. Copy the value stored in the ``source`` key to the ``destination`` key.
  1398. ``destination_db`` an alternative destination database. By default,
  1399. the ``destination`` key is created in the source Redis database.
  1400. ``replace`` whether the ``destination`` key should be removed before
  1401. copying the value to it. By default, the value is not copied if
  1402. the ``destination`` key already exists.
  1403. For more information see https://redis.io/commands/copy
  1404. """
  1405. params = [source, destination]
  1406. if destination_db is not None:
  1407. params.extend(["DB", destination_db])
  1408. if replace:
  1409. params.append("REPLACE")
  1410. return self.execute_command("COPY", *params)
  1411. def decrby(self, name: KeyT, amount: int = 1) -> ResponseT:
  1412. """
  1413. Decrements the value of ``key`` by ``amount``. If no key exists,
  1414. the value will be initialized as 0 - ``amount``
  1415. For more information see https://redis.io/commands/decrby
  1416. """
  1417. return self.execute_command("DECRBY", name, amount)
  1418. decr = decrby
  1419. def delete(self, *names: KeyT) -> ResponseT:
  1420. """
  1421. Delete one or more keys specified by ``names``
  1422. """
  1423. return self.execute_command("DEL", *names)
  1424. def __delitem__(self, name: KeyT):
  1425. self.delete(name)
  1426. def dump(self, name: KeyT) -> ResponseT:
  1427. """
  1428. Return a serialized version of the value stored at the specified key.
  1429. If key does not exist a nil bulk reply is returned.
  1430. For more information see https://redis.io/commands/dump
  1431. """
  1432. from redis.client import NEVER_DECODE
  1433. options = {}
  1434. options[NEVER_DECODE] = []
  1435. return self.execute_command("DUMP", name, **options)
  1436. def exists(self, *names: KeyT) -> ResponseT:
  1437. """
  1438. Returns the number of ``names`` that exist
  1439. For more information see https://redis.io/commands/exists
  1440. """
  1441. return self.execute_command("EXISTS", *names)
  1442. __contains__ = exists
  1443. def expire(
  1444. self,
  1445. name: KeyT,
  1446. time: ExpiryT,
  1447. nx: bool = False,
  1448. xx: bool = False,
  1449. gt: bool = False,
  1450. lt: bool = False,
  1451. ) -> ResponseT:
  1452. """
  1453. Set an expire flag on key ``name`` for ``time`` seconds with given
  1454. ``option``. ``time`` can be represented by an integer or a Python timedelta
  1455. object.
  1456. Valid options are:
  1457. NX -> Set expiry only when the key has no expiry
  1458. XX -> Set expiry only when the key has an existing expiry
  1459. GT -> Set expiry only when the new expiry is greater than current one
  1460. LT -> Set expiry only when the new expiry is less than current one
  1461. For more information see https://redis.io/commands/expire
  1462. """
  1463. if isinstance(time, datetime.timedelta):
  1464. time = int(time.total_seconds())
  1465. exp_option = list()
  1466. if nx:
  1467. exp_option.append("NX")
  1468. if xx:
  1469. exp_option.append("XX")
  1470. if gt:
  1471. exp_option.append("GT")
  1472. if lt:
  1473. exp_option.append("LT")
  1474. return self.execute_command("EXPIRE", name, time, *exp_option)
  1475. def expireat(
  1476. self,
  1477. name: KeyT,
  1478. when: AbsExpiryT,
  1479. nx: bool = False,
  1480. xx: bool = False,
  1481. gt: bool = False,
  1482. lt: bool = False,
  1483. ) -> ResponseT:
  1484. """
  1485. Set an expire flag on key ``name`` with given ``option``. ``when``
  1486. can be represented as an integer indicating unix time or a Python
  1487. datetime object.
  1488. Valid options are:
  1489. -> NX -- Set expiry only when the key has no expiry
  1490. -> XX -- Set expiry only when the key has an existing expiry
  1491. -> GT -- Set expiry only when the new expiry is greater than current one
  1492. -> LT -- Set expiry only when the new expiry is less than current one
  1493. For more information see https://redis.io/commands/expireat
  1494. """
  1495. if isinstance(when, datetime.datetime):
  1496. when = int(when.timestamp())
  1497. exp_option = list()
  1498. if nx:
  1499. exp_option.append("NX")
  1500. if xx:
  1501. exp_option.append("XX")
  1502. if gt:
  1503. exp_option.append("GT")
  1504. if lt:
  1505. exp_option.append("LT")
  1506. return self.execute_command("EXPIREAT", name, when, *exp_option)
  1507. def expiretime(self, key: str) -> int:
  1508. """
  1509. Returns the absolute Unix timestamp (since January 1, 1970) in seconds
  1510. at which the given key will expire.
  1511. For more information see https://redis.io/commands/expiretime
  1512. """
  1513. return self.execute_command("EXPIRETIME", key)
  1514. def get(self, name: KeyT) -> ResponseT:
  1515. """
  1516. Return the value at key ``name``, or None if the key doesn't exist
  1517. For more information see https://redis.io/commands/get
  1518. """
  1519. return self.execute_command("GET", name)
  1520. def getdel(self, name: KeyT) -> ResponseT:
  1521. """
  1522. Get the value at key ``name`` and delete the key. This command
  1523. is similar to GET, except for the fact that it also deletes
  1524. the key on success (if and only if the key's value type
  1525. is a string).
  1526. For more information see https://redis.io/commands/getdel
  1527. """
  1528. return self.execute_command("GETDEL", name)
  1529. def getex(
  1530. self,
  1531. name: KeyT,
  1532. ex: Union[ExpiryT, None] = None,
  1533. px: Union[ExpiryT, None] = None,
  1534. exat: Union[AbsExpiryT, None] = None,
  1535. pxat: Union[AbsExpiryT, None] = None,
  1536. persist: bool = False,
  1537. ) -> ResponseT:
  1538. """
  1539. Get the value of key and optionally set its expiration.
  1540. GETEX is similar to GET, but is a write command with
  1541. additional options. All time parameters can be given as
  1542. datetime.timedelta or integers.
  1543. ``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.
  1544. ``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.
  1545. ``exat`` sets an expire flag on key ``name`` for ``ex`` seconds,
  1546. specified in unix time.
  1547. ``pxat`` sets an expire flag on key ``name`` for ``ex`` milliseconds,
  1548. specified in unix time.
  1549. ``persist`` remove the time to live associated with ``name``.
  1550. For more information see https://redis.io/commands/getex
  1551. """
  1552. opset = {ex, px, exat, pxat}
  1553. if len(opset) > 2 or len(opset) > 1 and persist:
  1554. raise DataError(
  1555. "``ex``, ``px``, ``exat``, ``pxat``, "
  1556. "and ``persist`` are mutually exclusive."
  1557. )
  1558. pieces: list[EncodableT] = []
  1559. # similar to set command
  1560. if ex is not None:
  1561. pieces.append("EX")
  1562. if isinstance(ex, datetime.timedelta):
  1563. ex = int(ex.total_seconds())
  1564. pieces.append(ex)
  1565. if px is not None:
  1566. pieces.append("PX")
  1567. if isinstance(px, datetime.timedelta):
  1568. px = int(px.total_seconds() * 1000)
  1569. pieces.append(px)
  1570. # similar to pexpireat command
  1571. if exat is not None:
  1572. pieces.append("EXAT")
  1573. if isinstance(exat, datetime.datetime):
  1574. exat = int(exat.timestamp())
  1575. pieces.append(exat)
  1576. if pxat is not None:
  1577. pieces.append("PXAT")
  1578. if isinstance(pxat, datetime.datetime):
  1579. pxat = int(pxat.timestamp() * 1000)
  1580. pieces.append(pxat)
  1581. if persist:
  1582. pieces.append("PERSIST")
  1583. return self.execute_command("GETEX", name, *pieces)
  1584. def __getitem__(self, name: KeyT):
  1585. """
  1586. Return the value at key ``name``, raises a KeyError if the key
  1587. doesn't exist.
  1588. """
  1589. value = self.get(name)
  1590. if value is not None:
  1591. return value
  1592. raise KeyError(name)
  1593. def getbit(self, name: KeyT, offset: int) -> ResponseT:
  1594. """
  1595. Returns an integer indicating the value of ``offset`` in ``name``
  1596. For more information see https://redis.io/commands/getbit
  1597. """
  1598. return self.execute_command("GETBIT", name, offset)
  1599. def getrange(self, key: KeyT, start: int, end: int) -> ResponseT:
  1600. """
  1601. Returns the substring of the string value stored at ``key``,
  1602. determined by the offsets ``start`` and ``end`` (both are inclusive)
  1603. For more information see https://redis.io/commands/getrange
  1604. """
  1605. return self.execute_command("GETRANGE", key, start, end)
  1606. def getset(self, name: KeyT, value: EncodableT) -> ResponseT:
  1607. """
  1608. Sets the value at key ``name`` to ``value``
  1609. and returns the old value at key ``name`` atomically.
  1610. As per Redis 6.2, GETSET is considered deprecated.
  1611. Please use SET with GET parameter in new code.
  1612. For more information see https://redis.io/commands/getset
  1613. """
  1614. return self.execute_command("GETSET", name, value)
  1615. def incrby(self, name: KeyT, amount: int = 1) -> ResponseT:
  1616. """
  1617. Increments the value of ``key`` by ``amount``. If no key exists,
  1618. the value will be initialized as ``amount``
  1619. For more information see https://redis.io/commands/incrby
  1620. """
  1621. return self.execute_command("INCRBY", name, amount)
  1622. incr = incrby
  1623. def incrbyfloat(self, name: KeyT, amount: float = 1.0) -> ResponseT:
  1624. """
  1625. Increments the value at key ``name`` by floating ``amount``.
  1626. If no key exists, the value will be initialized as ``amount``
  1627. For more information see https://redis.io/commands/incrbyfloat
  1628. """
  1629. return self.execute_command("INCRBYFLOAT", name, amount)
  1630. def keys(self, pattern: PatternT = "*", **kwargs) -> ResponseT:
  1631. """
  1632. Returns a list of keys matching ``pattern``
  1633. For more information see https://redis.io/commands/keys
  1634. """
  1635. return self.execute_command("KEYS", pattern, **kwargs)
  1636. def lmove(
  1637. self, first_list: str, second_list: str, src: str = "LEFT", dest: str = "RIGHT"
  1638. ) -> ResponseT:
  1639. """
  1640. Atomically returns and removes the first/last element of a list,
  1641. pushing it as the first/last element on the destination list.
  1642. Returns the element being popped and pushed.
  1643. For more information see https://redis.io/commands/lmove
  1644. """
  1645. params = [first_list, second_list, src, dest]
  1646. return self.execute_command("LMOVE", *params)
  1647. def blmove(
  1648. self,
  1649. first_list: str,
  1650. second_list: str,
  1651. timeout: int,
  1652. src: str = "LEFT",
  1653. dest: str = "RIGHT",
  1654. ) -> ResponseT:
  1655. """
  1656. Blocking version of lmove.
  1657. For more information see https://redis.io/commands/blmove
  1658. """
  1659. params = [first_list, second_list, src, dest, timeout]
  1660. return self.execute_command("BLMOVE", *params)
  1661. def mget(self, keys: KeysT, *args: EncodableT) -> ResponseT:
  1662. """
  1663. Returns a list of values ordered identically to ``keys``
  1664. For more information see https://redis.io/commands/mget
  1665. """
  1666. from redis.client import EMPTY_RESPONSE
  1667. args = list_or_args(keys, args)
  1668. options = {}
  1669. if not args:
  1670. options[EMPTY_RESPONSE] = []
  1671. return self.execute_command("MGET", *args, **options)
  1672. def mset(self, mapping: Mapping[AnyKeyT, EncodableT]) -> ResponseT:
  1673. """
  1674. Sets key/values based on a mapping. Mapping is a dictionary of
  1675. key/value pairs. Both keys and values should be strings or types that
  1676. can be cast to a string via str().
  1677. For more information see https://redis.io/commands/mset
  1678. """
  1679. items = []
  1680. for pair in mapping.items():
  1681. items.extend(pair)
  1682. return self.execute_command("MSET", *items)
  1683. def msetnx(self, mapping: Mapping[AnyKeyT, EncodableT]) -> ResponseT:
  1684. """
  1685. Sets key/values based on a mapping if none of the keys are already set.
  1686. Mapping is a dictionary of key/value pairs. Both keys and values
  1687. should be strings or types that can be cast to a string via str().
  1688. Returns a boolean indicating if the operation was successful.
  1689. For more information see https://redis.io/commands/msetnx
  1690. """
  1691. items = []
  1692. for pair in mapping.items():
  1693. items.extend(pair)
  1694. return self.execute_command("MSETNX", *items)
  1695. def move(self, name: KeyT, db: int) -> ResponseT:
  1696. """
  1697. Moves the key ``name`` to a different Redis database ``db``
  1698. For more information see https://redis.io/commands/move
  1699. """
  1700. return self.execute_command("MOVE", name, db)
  1701. def persist(self, name: KeyT) -> ResponseT:
  1702. """
  1703. Removes an expiration on ``name``
  1704. For more information see https://redis.io/commands/persist
  1705. """
  1706. return self.execute_command("PERSIST", name)
  1707. def pexpire(
  1708. self,
  1709. name: KeyT,
  1710. time: ExpiryT,
  1711. nx: bool = False,
  1712. xx: bool = False,
  1713. gt: bool = False,
  1714. lt: bool = False,
  1715. ) -> ResponseT:
  1716. """
  1717. Set an expire flag on key ``name`` for ``time`` milliseconds
  1718. with given ``option``. ``time`` can be represented by an
  1719. integer or a Python timedelta object.
  1720. Valid options are:
  1721. NX -> Set expiry only when the key has no expiry
  1722. XX -> Set expiry only when the key has an existing expiry
  1723. GT -> Set expiry only when the new expiry is greater than current one
  1724. LT -> Set expiry only when the new expiry is less than current one
  1725. For more information see https://redis.io/commands/pexpire
  1726. """
  1727. if isinstance(time, datetime.timedelta):
  1728. time = int(time.total_seconds() * 1000)
  1729. exp_option = list()
  1730. if nx:
  1731. exp_option.append("NX")
  1732. if xx:
  1733. exp_option.append("XX")
  1734. if gt:
  1735. exp_option.append("GT")
  1736. if lt:
  1737. exp_option.append("LT")
  1738. return self.execute_command("PEXPIRE", name, time, *exp_option)
  1739. def pexpireat(
  1740. self,
  1741. name: KeyT,
  1742. when: AbsExpiryT,
  1743. nx: bool = False,
  1744. xx: bool = False,
  1745. gt: bool = False,
  1746. lt: bool = False,
  1747. ) -> ResponseT:
  1748. """
  1749. Set an expire flag on key ``name`` with given ``option``. ``when``
  1750. can be represented as an integer representing unix time in
  1751. milliseconds (unix time * 1000) or a Python datetime object.
  1752. Valid options are:
  1753. NX -> Set expiry only when the key has no expiry
  1754. XX -> Set expiry only when the key has an existing expiry
  1755. GT -> Set expiry only when the new expiry is greater than current one
  1756. LT -> Set expiry only when the new expiry is less than current one
  1757. For more information see https://redis.io/commands/pexpireat
  1758. """
  1759. if isinstance(when, datetime.datetime):
  1760. when = int(when.timestamp() * 1000)
  1761. exp_option = list()
  1762. if nx:
  1763. exp_option.append("NX")
  1764. if xx:
  1765. exp_option.append("XX")
  1766. if gt:
  1767. exp_option.append("GT")
  1768. if lt:
  1769. exp_option.append("LT")
  1770. return self.execute_command("PEXPIREAT", name, when, *exp_option)
  1771. def pexpiretime(self, key: str) -> int:
  1772. """
  1773. Returns the absolute Unix timestamp (since January 1, 1970) in milliseconds
  1774. at which the given key will expire.
  1775. For more information see https://redis.io/commands/pexpiretime
  1776. """
  1777. return self.execute_command("PEXPIRETIME", key)
  1778. def psetex(self, name: KeyT, time_ms: ExpiryT, value: EncodableT):
  1779. """
  1780. Set the value of key ``name`` to ``value`` that expires in ``time_ms``
  1781. milliseconds. ``time_ms`` can be represented by an integer or a Python
  1782. timedelta object
  1783. For more information see https://redis.io/commands/psetex
  1784. """
  1785. if isinstance(time_ms, datetime.timedelta):
  1786. time_ms = int(time_ms.total_seconds() * 1000)
  1787. return self.execute_command("PSETEX", name, time_ms, value)
  1788. def pttl(self, name: KeyT) -> ResponseT:
  1789. """
  1790. Returns the number of milliseconds until the key ``name`` will expire
  1791. For more information see https://redis.io/commands/pttl
  1792. """
  1793. return self.execute_command("PTTL", name)
  1794. def hrandfield(
  1795. self, key: str, count: int = None, withvalues: bool = False
  1796. ) -> ResponseT:
  1797. """
  1798. Return a random field from the hash value stored at key.
  1799. count: if the argument is positive, return an array of distinct fields.
  1800. If called with a negative count, the behavior changes and the command
  1801. is allowed to return the same field multiple times. In this case,
  1802. the number of returned fields is the absolute value of the
  1803. specified count.
  1804. withvalues: The optional WITHVALUES modifier changes the reply so it
  1805. includes the respective values of the randomly selected hash fields.
  1806. For more information see https://redis.io/commands/hrandfield
  1807. """
  1808. params = []
  1809. if count is not None:
  1810. params.append(count)
  1811. if withvalues:
  1812. params.append("WITHVALUES")
  1813. return self.execute_command("HRANDFIELD", key, *params)
  1814. def randomkey(self, **kwargs) -> ResponseT:
  1815. """
  1816. Returns the name of a random key
  1817. For more information see https://redis.io/commands/randomkey
  1818. """
  1819. return self.execute_command("RANDOMKEY", **kwargs)
  1820. def rename(self, src: KeyT, dst: KeyT) -> ResponseT:
  1821. """
  1822. Rename key ``src`` to ``dst``
  1823. For more information see https://redis.io/commands/rename
  1824. """
  1825. return self.execute_command("RENAME", src, dst)
  1826. def renamenx(self, src: KeyT, dst: KeyT):
  1827. """
  1828. Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist
  1829. For more information see https://redis.io/commands/renamenx
  1830. """
  1831. return self.execute_command("RENAMENX", src, dst)
  1832. def restore(
  1833. self,
  1834. name: KeyT,
  1835. ttl: float,
  1836. value: EncodableT,
  1837. replace: bool = False,
  1838. absttl: bool = False,
  1839. idletime: Union[int, None] = None,
  1840. frequency: Union[int, None] = None,
  1841. ) -> ResponseT:
  1842. """
  1843. Create a key using the provided serialized value, previously obtained
  1844. using DUMP.
  1845. ``replace`` allows an existing key on ``name`` to be overridden. If
  1846. it's not specified an error is raised on collision.
  1847. ``absttl`` if True, specified ``ttl`` should represent an absolute Unix
  1848. timestamp in milliseconds in which the key will expire. (Redis 5.0 or
  1849. greater).
  1850. ``idletime`` Used for eviction, this is the number of seconds the
  1851. key must be idle, prior to execution.
  1852. ``frequency`` Used for eviction, this is the frequency counter of
  1853. the object stored at the key, prior to execution.
  1854. For more information see https://redis.io/commands/restore
  1855. """
  1856. params = [name, ttl, value]
  1857. if replace:
  1858. params.append("REPLACE")
  1859. if absttl:
  1860. params.append("ABSTTL")
  1861. if idletime is not None:
  1862. params.append("IDLETIME")
  1863. try:
  1864. params.append(int(idletime))
  1865. except ValueError:
  1866. raise DataError("idletimemust be an integer")
  1867. if frequency is not None:
  1868. params.append("FREQ")
  1869. try:
  1870. params.append(int(frequency))
  1871. except ValueError:
  1872. raise DataError("frequency must be an integer")
  1873. return self.execute_command("RESTORE", *params)
  1874. def set(
  1875. self,
  1876. name: KeyT,
  1877. value: EncodableT,
  1878. ex: Union[ExpiryT, None] = None,
  1879. px: Union[ExpiryT, None] = None,
  1880. nx: bool = False,
  1881. xx: bool = False,
  1882. keepttl: bool = False,
  1883. get: bool = False,
  1884. exat: Union[AbsExpiryT, None] = None,
  1885. pxat: Union[AbsExpiryT, None] = None,
  1886. ) -> ResponseT:
  1887. """
  1888. Set the value at key ``name`` to ``value``
  1889. ``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.
  1890. ``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.
  1891. ``nx`` if set to True, set the value at key ``name`` to ``value`` only
  1892. if it does not exist.
  1893. ``xx`` if set to True, set the value at key ``name`` to ``value`` only
  1894. if it already exists.
  1895. ``keepttl`` if True, retain the time to live associated with the key.
  1896. (Available since Redis 6.0)
  1897. ``get`` if True, set the value at key ``name`` to ``value`` and return
  1898. the old value stored at key, or None if the key did not exist.
  1899. (Available since Redis 6.2)
  1900. ``exat`` sets an expire flag on key ``name`` for ``ex`` seconds,
  1901. specified in unix time.
  1902. ``pxat`` sets an expire flag on key ``name`` for ``ex`` milliseconds,
  1903. specified in unix time.
  1904. For more information see https://redis.io/commands/set
  1905. """
  1906. pieces: list[EncodableT] = [name, value]
  1907. options = {}
  1908. if ex is not None:
  1909. pieces.append("EX")
  1910. if isinstance(ex, datetime.timedelta):
  1911. pieces.append(int(ex.total_seconds()))
  1912. elif isinstance(ex, int):
  1913. pieces.append(ex)
  1914. elif isinstance(ex, str) and ex.isdigit():
  1915. pieces.append(int(ex))
  1916. else:
  1917. raise DataError("ex must be datetime.timedelta or int")
  1918. if px is not None:
  1919. pieces.append("PX")
  1920. if isinstance(px, datetime.timedelta):
  1921. pieces.append(int(px.total_seconds() * 1000))
  1922. elif isinstance(px, int):
  1923. pieces.append(px)
  1924. else:
  1925. raise DataError("px must be datetime.timedelta or int")
  1926. if exat is not None:
  1927. pieces.append("EXAT")
  1928. if isinstance(exat, datetime.datetime):
  1929. exat = int(exat.timestamp())
  1930. pieces.append(exat)
  1931. if pxat is not None:
  1932. pieces.append("PXAT")
  1933. if isinstance(pxat, datetime.datetime):
  1934. pxat = int(pxat.timestamp() * 1000)
  1935. pieces.append(pxat)
  1936. if keepttl:
  1937. pieces.append("KEEPTTL")
  1938. if nx:
  1939. pieces.append("NX")
  1940. if xx:
  1941. pieces.append("XX")
  1942. if get:
  1943. pieces.append("GET")
  1944. options["get"] = True
  1945. return self.execute_command("SET", *pieces, **options)
  1946. def __setitem__(self, name: KeyT, value: EncodableT):
  1947. self.set(name, value)
  1948. def setbit(self, name: KeyT, offset: int, value: int) -> ResponseT:
  1949. """
  1950. Flag the ``offset`` in ``name`` as ``value``. Returns an integer
  1951. indicating the previous value of ``offset``.
  1952. For more information see https://redis.io/commands/setbit
  1953. """
  1954. value = value and 1 or 0
  1955. return self.execute_command("SETBIT", name, offset, value)
  1956. def setex(self, name: KeyT, time: ExpiryT, value: EncodableT) -> ResponseT:
  1957. """
  1958. Set the value of key ``name`` to ``value`` that expires in ``time``
  1959. seconds. ``time`` can be represented by an integer or a Python
  1960. timedelta object.
  1961. For more information see https://redis.io/commands/setex
  1962. """
  1963. if isinstance(time, datetime.timedelta):
  1964. time = int(time.total_seconds())
  1965. return self.execute_command("SETEX", name, time, value)
  1966. def setnx(self, name: KeyT, value: EncodableT) -> ResponseT:
  1967. """
  1968. Set the value of key ``name`` to ``value`` if key doesn't exist
  1969. For more information see https://redis.io/commands/setnx
  1970. """
  1971. return self.execute_command("SETNX", name, value)
  1972. def setrange(self, name: KeyT, offset: int, value: EncodableT) -> ResponseT:
  1973. """
  1974. Overwrite bytes in the value of ``name`` starting at ``offset`` with
  1975. ``value``. If ``offset`` plus the length of ``value`` exceeds the
  1976. length of the original value, the new value will be larger than before.
  1977. If ``offset`` exceeds the length of the original value, null bytes
  1978. will be used to pad between the end of the previous value and the start
  1979. of what's being injected.
  1980. Returns the length of the new string.
  1981. For more information see https://redis.io/commands/setrange
  1982. """
  1983. return self.execute_command("SETRANGE", name, offset, value)
  1984. def stralgo(
  1985. self,
  1986. algo: Literal["LCS"],
  1987. value1: KeyT,
  1988. value2: KeyT,
  1989. specific_argument: Union[Literal["strings"], Literal["keys"]] = "strings",
  1990. len: bool = False,
  1991. idx: bool = False,
  1992. minmatchlen: Union[int, None] = None,
  1993. withmatchlen: bool = False,
  1994. **kwargs,
  1995. ) -> ResponseT:
  1996. """
  1997. Implements complex algorithms that operate on strings.
  1998. Right now the only algorithm implemented is the LCS algorithm
  1999. (longest common substring). However new algorithms could be
  2000. implemented in the future.
  2001. ``algo`` Right now must be LCS
  2002. ``value1`` and ``value2`` Can be two strings or two keys
  2003. ``specific_argument`` Specifying if the arguments to the algorithm
  2004. will be keys or strings. strings is the default.
  2005. ``len`` Returns just the len of the match.
  2006. ``idx`` Returns the match positions in each string.
  2007. ``minmatchlen`` Restrict the list of matches to the ones of a given
  2008. minimal length. Can be provided only when ``idx`` set to True.
  2009. ``withmatchlen`` Returns the matches with the len of the match.
  2010. Can be provided only when ``idx`` set to True.
  2011. For more information see https://redis.io/commands/stralgo
  2012. """
  2013. # check validity
  2014. supported_algo = ["LCS"]
  2015. if algo not in supported_algo:
  2016. supported_algos_str = ", ".join(supported_algo)
  2017. raise DataError(f"The supported algorithms are: {supported_algos_str}")
  2018. if specific_argument not in ["keys", "strings"]:
  2019. raise DataError("specific_argument can be only keys or strings")
  2020. if len and idx:
  2021. raise DataError("len and idx cannot be provided together.")
  2022. pieces: list[EncodableT] = [algo, specific_argument.upper(), value1, value2]
  2023. if len:
  2024. pieces.append(b"LEN")
  2025. if idx:
  2026. pieces.append(b"IDX")
  2027. try:
  2028. int(minmatchlen)
  2029. pieces.extend([b"MINMATCHLEN", minmatchlen])
  2030. except TypeError:
  2031. pass
  2032. if withmatchlen:
  2033. pieces.append(b"WITHMATCHLEN")
  2034. return self.execute_command(
  2035. "STRALGO",
  2036. *pieces,
  2037. len=len,
  2038. idx=idx,
  2039. minmatchlen=minmatchlen,
  2040. withmatchlen=withmatchlen,
  2041. **kwargs,
  2042. )
  2043. def strlen(self, name: KeyT) -> ResponseT:
  2044. """
  2045. Return the number of bytes stored in the value of ``name``
  2046. For more information see https://redis.io/commands/strlen
  2047. """
  2048. return self.execute_command("STRLEN", name)
  2049. def substr(self, name: KeyT, start: int, end: int = -1) -> ResponseT:
  2050. """
  2051. Return a substring of the string at key ``name``. ``start`` and ``end``
  2052. are 0-based integers specifying the portion of the string to return.
  2053. """
  2054. return self.execute_command("SUBSTR", name, start, end)
  2055. def touch(self, *args: KeyT) -> ResponseT:
  2056. """
  2057. Alters the last access time of a key(s) ``*args``. A key is ignored
  2058. if it does not exist.
  2059. For more information see https://redis.io/commands/touch
  2060. """
  2061. return self.execute_command("TOUCH", *args)
  2062. def ttl(self, name: KeyT) -> ResponseT:
  2063. """
  2064. Returns the number of seconds until the key ``name`` will expire
  2065. For more information see https://redis.io/commands/ttl
  2066. """
  2067. return self.execute_command("TTL", name)
  2068. def type(self, name: KeyT) -> ResponseT:
  2069. """
  2070. Returns the type of key ``name``
  2071. For more information see https://redis.io/commands/type
  2072. """
  2073. return self.execute_command("TYPE", name)
  2074. def watch(self, *names: KeyT) -> None:
  2075. """
  2076. Watches the values at keys ``names``, or None if the key doesn't exist
  2077. For more information see https://redis.io/commands/watch
  2078. """
  2079. warnings.warn(DeprecationWarning("Call WATCH from a Pipeline object"))
  2080. def unwatch(self) -> None:
  2081. """
  2082. Unwatches the value at key ``name``, or None of the key doesn't exist
  2083. For more information see https://redis.io/commands/unwatch
  2084. """
  2085. warnings.warn(DeprecationWarning("Call UNWATCH from a Pipeline object"))
  2086. def unlink(self, *names: KeyT) -> ResponseT:
  2087. """
  2088. Unlink one or more keys specified by ``names``
  2089. For more information see https://redis.io/commands/unlink
  2090. """
  2091. return self.execute_command("UNLINK", *names)
  2092. def lcs(
  2093. self,
  2094. key1: str,
  2095. key2: str,
  2096. len: Optional[bool] = False,
  2097. idx: Optional[bool] = False,
  2098. minmatchlen: Optional[int] = 0,
  2099. withmatchlen: Optional[bool] = False,
  2100. ) -> Union[str, int, list]:
  2101. """
  2102. Find the longest common subsequence between ``key1`` and ``key2``.
  2103. If ``len`` is true the length of the match will will be returned.
  2104. If ``idx`` is true the match position in each strings will be returned.
  2105. ``minmatchlen`` restrict the list of matches to the ones of
  2106. the given ``minmatchlen``.
  2107. If ``withmatchlen`` the length of the match also will be returned.
  2108. For more information see https://redis.io/commands/lcs
  2109. """
  2110. pieces = [key1, key2]
  2111. if len:
  2112. pieces.append("LEN")
  2113. if idx:
  2114. pieces.append("IDX")
  2115. if minmatchlen != 0:
  2116. pieces.extend(["MINMATCHLEN", minmatchlen])
  2117. if withmatchlen:
  2118. pieces.append("WITHMATCHLEN")
  2119. return self.execute_command("LCS", *pieces)
  2120. class AsyncBasicKeyCommands(BasicKeyCommands):
  2121. def __delitem__(self, name: KeyT):
  2122. raise TypeError("Async Redis client does not support class deletion")
  2123. def __contains__(self, name: KeyT):
  2124. raise TypeError("Async Redis client does not support class inclusion")
  2125. def __getitem__(self, name: KeyT):
  2126. raise TypeError("Async Redis client does not support class retrieval")
  2127. def __setitem__(self, name: KeyT, value: EncodableT):
  2128. raise TypeError("Async Redis client does not support class assignment")
  2129. async def watch(self, *names: KeyT) -> None:
  2130. return super().watch(*names)
  2131. async def unwatch(self) -> None:
  2132. return super().unwatch()
  2133. class ListCommands(CommandsProtocol):
  2134. """
  2135. Redis commands for List data type.
  2136. see: https://redis.io/topics/data-types#lists
  2137. """
  2138. def blpop(
  2139. self, keys: List, timeout: Optional[int] = 0
  2140. ) -> Union[Awaitable[list], list]:
  2141. """
  2142. LPOP a value off of the first non-empty list
  2143. named in the ``keys`` list.
  2144. If none of the lists in ``keys`` has a value to LPOP, then block
  2145. for ``timeout`` seconds, or until a value gets pushed on to one
  2146. of the lists.
  2147. If timeout is 0, then block indefinitely.
  2148. For more information see https://redis.io/commands/blpop
  2149. """
  2150. if timeout is None:
  2151. timeout = 0
  2152. keys = list_or_args(keys, None)
  2153. keys.append(timeout)
  2154. return self.execute_command("BLPOP", *keys)
  2155. def brpop(
  2156. self, keys: List, timeout: Optional[int] = 0
  2157. ) -> Union[Awaitable[list], list]:
  2158. """
  2159. RPOP a value off of the first non-empty list
  2160. named in the ``keys`` list.
  2161. If none of the lists in ``keys`` has a value to RPOP, then block
  2162. for ``timeout`` seconds, or until a value gets pushed on to one
  2163. of the lists.
  2164. If timeout is 0, then block indefinitely.
  2165. For more information see https://redis.io/commands/brpop
  2166. """
  2167. if timeout is None:
  2168. timeout = 0
  2169. keys = list_or_args(keys, None)
  2170. keys.append(timeout)
  2171. return self.execute_command("BRPOP", *keys)
  2172. def brpoplpush(
  2173. self, src: str, dst: str, timeout: Optional[int] = 0
  2174. ) -> Union[Awaitable[Optional[str]], Optional[str]]:
  2175. """
  2176. Pop a value off the tail of ``src``, push it on the head of ``dst``
  2177. and then return it.
  2178. This command blocks until a value is in ``src`` or until ``timeout``
  2179. seconds elapse, whichever is first. A ``timeout`` value of 0 blocks
  2180. forever.
  2181. For more information see https://redis.io/commands/brpoplpush
  2182. """
  2183. if timeout is None:
  2184. timeout = 0
  2185. return self.execute_command("BRPOPLPUSH", src, dst, timeout)
  2186. def blmpop(
  2187. self,
  2188. timeout: float,
  2189. numkeys: int,
  2190. *args: List[str],
  2191. direction: str,
  2192. count: Optional[int] = 1,
  2193. ) -> Optional[list]:
  2194. """
  2195. Pop ``count`` values (default 1) from first non-empty in the list
  2196. of provided key names.
  2197. When all lists are empty this command blocks the connection until another
  2198. client pushes to it or until the timeout, timeout of 0 blocks indefinitely
  2199. For more information see https://redis.io/commands/blmpop
  2200. """
  2201. args = [timeout, numkeys, *args, direction, "COUNT", count]
  2202. return self.execute_command("BLMPOP", *args)
  2203. def lmpop(
  2204. self,
  2205. num_keys: int,
  2206. *args: List[str],
  2207. direction: str,
  2208. count: Optional[int] = 1,
  2209. ) -> Union[Awaitable[list], list]:
  2210. """
  2211. Pop ``count`` values (default 1) first non-empty list key from the list
  2212. of args provided key names.
  2213. For more information see https://redis.io/commands/lmpop
  2214. """
  2215. args = [num_keys] + list(args) + [direction]
  2216. if count != 1:
  2217. args.extend(["COUNT", count])
  2218. return self.execute_command("LMPOP", *args)
  2219. def lindex(
  2220. self, name: str, index: int
  2221. ) -> Union[Awaitable[Optional[str]], Optional[str]]:
  2222. """
  2223. Return the item from list ``name`` at position ``index``
  2224. Negative indexes are supported and will return an item at the
  2225. end of the list
  2226. For more information see https://redis.io/commands/lindex
  2227. """
  2228. return self.execute_command("LINDEX", name, index)
  2229. def linsert(
  2230. self, name: str, where: str, refvalue: str, value: str
  2231. ) -> Union[Awaitable[int], int]:
  2232. """
  2233. Insert ``value`` in list ``name`` either immediately before or after
  2234. [``where``] ``refvalue``
  2235. Returns the new length of the list on success or -1 if ``refvalue``
  2236. is not in the list.
  2237. For more information see https://redis.io/commands/linsert
  2238. """
  2239. return self.execute_command("LINSERT", name, where, refvalue, value)
  2240. def llen(self, name: str) -> Union[Awaitable[int], int]:
  2241. """
  2242. Return the length of the list ``name``
  2243. For more information see https://redis.io/commands/llen
  2244. """
  2245. return self.execute_command("LLEN", name)
  2246. def lpop(
  2247. self,
  2248. name: str,
  2249. count: Optional[int] = None,
  2250. ) -> Union[Awaitable[Union[str, List, None]], Union[str, List, None]]:
  2251. """
  2252. Removes and returns the first elements of the list ``name``.
  2253. By default, the command pops a single element from the beginning of
  2254. the list. When provided with the optional ``count`` argument, the reply
  2255. will consist of up to count elements, depending on the list's length.
  2256. For more information see https://redis.io/commands/lpop
  2257. """
  2258. if count is not None:
  2259. return self.execute_command("LPOP", name, count)
  2260. else:
  2261. return self.execute_command("LPOP", name)
  2262. def lpush(self, name: str, *values: FieldT) -> Union[Awaitable[int], int]:
  2263. """
  2264. Push ``values`` onto the head of the list ``name``
  2265. For more information see https://redis.io/commands/lpush
  2266. """
  2267. return self.execute_command("LPUSH", name, *values)
  2268. def lpushx(self, name: str, *values: FieldT) -> Union[Awaitable[int], int]:
  2269. """
  2270. Push ``value`` onto the head of the list ``name`` if ``name`` exists
  2271. For more information see https://redis.io/commands/lpushx
  2272. """
  2273. return self.execute_command("LPUSHX", name, *values)
  2274. def lrange(self, name: str, start: int, end: int) -> Union[Awaitable[list], list]:
  2275. """
  2276. Return a slice of the list ``name`` between
  2277. position ``start`` and ``end``
  2278. ``start`` and ``end`` can be negative numbers just like
  2279. Python slicing notation
  2280. For more information see https://redis.io/commands/lrange
  2281. """
  2282. return self.execute_command("LRANGE", name, start, end)
  2283. def lrem(self, name: str, count: int, value: str) -> Union[Awaitable[int], int]:
  2284. """
  2285. Remove the first ``count`` occurrences of elements equal to ``value``
  2286. from the list stored at ``name``.
  2287. The count argument influences the operation in the following ways:
  2288. count > 0: Remove elements equal to value moving from head to tail.
  2289. count < 0: Remove elements equal to value moving from tail to head.
  2290. count = 0: Remove all elements equal to value.
  2291. For more information see https://redis.io/commands/lrem
  2292. """
  2293. return self.execute_command("LREM", name, count, value)
  2294. def lset(self, name: str, index: int, value: str) -> Union[Awaitable[str], str]:
  2295. """
  2296. Set element at ``index`` of list ``name`` to ``value``
  2297. For more information see https://redis.io/commands/lset
  2298. """
  2299. return self.execute_command("LSET", name, index, value)
  2300. def ltrim(self, name: str, start: int, end: int) -> Union[Awaitable[str], str]:
  2301. """
  2302. Trim the list ``name``, removing all values not within the slice
  2303. between ``start`` and ``end``
  2304. ``start`` and ``end`` can be negative numbers just like
  2305. Python slicing notation
  2306. For more information see https://redis.io/commands/ltrim
  2307. """
  2308. return self.execute_command("LTRIM", name, start, end)
  2309. def rpop(
  2310. self,
  2311. name: str,
  2312. count: Optional[int] = None,
  2313. ) -> Union[Awaitable[Union[str, List, None]], Union[str, List, None]]:
  2314. """
  2315. Removes and returns the last elements of the list ``name``.
  2316. By default, the command pops a single element from the end of the list.
  2317. When provided with the optional ``count`` argument, the reply will
  2318. consist of up to count elements, depending on the list's length.
  2319. For more information see https://redis.io/commands/rpop
  2320. """
  2321. if count is not None:
  2322. return self.execute_command("RPOP", name, count)
  2323. else:
  2324. return self.execute_command("RPOP", name)
  2325. def rpoplpush(self, src: str, dst: str) -> Union[Awaitable[str], str]:
  2326. """
  2327. RPOP a value off of the ``src`` list and atomically LPUSH it
  2328. on to the ``dst`` list. Returns the value.
  2329. For more information see https://redis.io/commands/rpoplpush
  2330. """
  2331. return self.execute_command("RPOPLPUSH", src, dst)
  2332. def rpush(self, name: str, *values: FieldT) -> Union[Awaitable[int], int]:
  2333. """
  2334. Push ``values`` onto the tail of the list ``name``
  2335. For more information see https://redis.io/commands/rpush
  2336. """
  2337. return self.execute_command("RPUSH", name, *values)
  2338. def rpushx(self, name: str, *values: str) -> Union[Awaitable[int], int]:
  2339. """
  2340. Push ``value`` onto the tail of the list ``name`` if ``name`` exists
  2341. For more information see https://redis.io/commands/rpushx
  2342. """
  2343. return self.execute_command("RPUSHX", name, *values)
  2344. def lpos(
  2345. self,
  2346. name: str,
  2347. value: str,
  2348. rank: Optional[int] = None,
  2349. count: Optional[int] = None,
  2350. maxlen: Optional[int] = None,
  2351. ) -> Union[str, List, None]:
  2352. """
  2353. Get position of ``value`` within the list ``name``
  2354. If specified, ``rank`` indicates the "rank" of the first element to
  2355. return in case there are multiple copies of ``value`` in the list.
  2356. By default, LPOS returns the position of the first occurrence of
  2357. ``value`` in the list. When ``rank`` 2, LPOS returns the position of
  2358. the second ``value`` in the list. If ``rank`` is negative, LPOS
  2359. searches the list in reverse. For example, -1 would return the
  2360. position of the last occurrence of ``value`` and -2 would return the
  2361. position of the next to last occurrence of ``value``.
  2362. If specified, ``count`` indicates that LPOS should return a list of
  2363. up to ``count`` positions. A ``count`` of 2 would return a list of
  2364. up to 2 positions. A ``count`` of 0 returns a list of all positions
  2365. matching ``value``. When ``count`` is specified and but ``value``
  2366. does not exist in the list, an empty list is returned.
  2367. If specified, ``maxlen`` indicates the maximum number of list
  2368. elements to scan. A ``maxlen`` of 1000 will only return the
  2369. position(s) of items within the first 1000 entries in the list.
  2370. A ``maxlen`` of 0 (the default) will scan the entire list.
  2371. For more information see https://redis.io/commands/lpos
  2372. """
  2373. pieces: list[EncodableT] = [name, value]
  2374. if rank is not None:
  2375. pieces.extend(["RANK", rank])
  2376. if count is not None:
  2377. pieces.extend(["COUNT", count])
  2378. if maxlen is not None:
  2379. pieces.extend(["MAXLEN", maxlen])
  2380. return self.execute_command("LPOS", *pieces)
  2381. def sort(
  2382. self,
  2383. name: str,
  2384. start: Optional[int] = None,
  2385. num: Optional[int] = None,
  2386. by: Optional[str] = None,
  2387. get: Optional[List[str]] = None,
  2388. desc: bool = False,
  2389. alpha: bool = False,
  2390. store: Optional[str] = None,
  2391. groups: Optional[bool] = False,
  2392. ) -> Union[List, int]:
  2393. """
  2394. Sort and return the list, set or sorted set at ``name``.
  2395. ``start`` and ``num`` allow for paging through the sorted data
  2396. ``by`` allows using an external key to weight and sort the items.
  2397. Use an "*" to indicate where in the key the item value is located
  2398. ``get`` allows for returning items from external keys rather than the
  2399. sorted data itself. Use an "*" to indicate where in the key
  2400. the item value is located
  2401. ``desc`` allows for reversing the sort
  2402. ``alpha`` allows for sorting lexicographically rather than numerically
  2403. ``store`` allows for storing the result of the sort into
  2404. the key ``store``
  2405. ``groups`` if set to True and if ``get`` contains at least two
  2406. elements, sort will return a list of tuples, each containing the
  2407. values fetched from the arguments to ``get``.
  2408. For more information see https://redis.io/commands/sort
  2409. """
  2410. if (start is not None and num is None) or (num is not None and start is None):
  2411. raise DataError("``start`` and ``num`` must both be specified")
  2412. pieces: list[EncodableT] = [name]
  2413. if by is not None:
  2414. pieces.extend([b"BY", by])
  2415. if start is not None and num is not None:
  2416. pieces.extend([b"LIMIT", start, num])
  2417. if get is not None:
  2418. # If get is a string assume we want to get a single value.
  2419. # Otherwise assume it's an interable and we want to get multiple
  2420. # values. We can't just iterate blindly because strings are
  2421. # iterable.
  2422. if isinstance(get, (bytes, str)):
  2423. pieces.extend([b"GET", get])
  2424. else:
  2425. for g in get:
  2426. pieces.extend([b"GET", g])
  2427. if desc:
  2428. pieces.append(b"DESC")
  2429. if alpha:
  2430. pieces.append(b"ALPHA")
  2431. if store is not None:
  2432. pieces.extend([b"STORE", store])
  2433. if groups:
  2434. if not get or isinstance(get, (bytes, str)) or len(get) < 2:
  2435. raise DataError(
  2436. 'when using "groups" the "get" argument '
  2437. "must be specified and contain at least "
  2438. "two keys"
  2439. )
  2440. options = {"groups": len(get) if groups else None}
  2441. return self.execute_command("SORT", *pieces, **options)
  2442. def sort_ro(
  2443. self,
  2444. key: str,
  2445. start: Optional[int] = None,
  2446. num: Optional[int] = None,
  2447. by: Optional[str] = None,
  2448. get: Optional[List[str]] = None,
  2449. desc: bool = False,
  2450. alpha: bool = False,
  2451. ) -> list:
  2452. """
  2453. Returns the elements contained in the list, set or sorted set at key.
  2454. (read-only variant of the SORT command)
  2455. ``start`` and ``num`` allow for paging through the sorted data
  2456. ``by`` allows using an external key to weight and sort the items.
  2457. Use an "*" to indicate where in the key the item value is located
  2458. ``get`` allows for returning items from external keys rather than the
  2459. sorted data itself. Use an "*" to indicate where in the key
  2460. the item value is located
  2461. ``desc`` allows for reversing the sort
  2462. ``alpha`` allows for sorting lexicographically rather than numerically
  2463. For more information see https://redis.io/commands/sort_ro
  2464. """
  2465. return self.sort(
  2466. key, start=start, num=num, by=by, get=get, desc=desc, alpha=alpha
  2467. )
  2468. AsyncListCommands = ListCommands
  2469. class ScanCommands(CommandsProtocol):
  2470. """
  2471. Redis SCAN commands.
  2472. see: https://redis.io/commands/scan
  2473. """
  2474. def scan(
  2475. self,
  2476. cursor: int = 0,
  2477. match: Union[PatternT, None] = None,
  2478. count: Union[int, None] = None,
  2479. _type: Union[str, None] = None,
  2480. **kwargs,
  2481. ) -> ResponseT:
  2482. """
  2483. Incrementally return lists of key names. Also return a cursor
  2484. indicating the scan position.
  2485. ``match`` allows for filtering the keys by pattern
  2486. ``count`` provides a hint to Redis about the number of keys to
  2487. return per batch.
  2488. ``_type`` filters the returned values by a particular Redis type.
  2489. Stock Redis instances allow for the following types:
  2490. HASH, LIST, SET, STREAM, STRING, ZSET
  2491. Additionally, Redis modules can expose other types as well.
  2492. For more information see https://redis.io/commands/scan
  2493. """
  2494. pieces: list[EncodableT] = [cursor]
  2495. if match is not None:
  2496. pieces.extend([b"MATCH", match])
  2497. if count is not None:
  2498. pieces.extend([b"COUNT", count])
  2499. if _type is not None:
  2500. pieces.extend([b"TYPE", _type])
  2501. return self.execute_command("SCAN", *pieces, **kwargs)
  2502. def scan_iter(
  2503. self,
  2504. match: Union[PatternT, None] = None,
  2505. count: Union[int, None] = None,
  2506. _type: Union[str, None] = None,
  2507. **kwargs,
  2508. ) -> Iterator:
  2509. """
  2510. Make an iterator using the SCAN command so that the client doesn't
  2511. need to remember the cursor position.
  2512. ``match`` allows for filtering the keys by pattern
  2513. ``count`` provides a hint to Redis about the number of keys to
  2514. return per batch.
  2515. ``_type`` filters the returned values by a particular Redis type.
  2516. Stock Redis instances allow for the following types:
  2517. HASH, LIST, SET, STREAM, STRING, ZSET
  2518. Additionally, Redis modules can expose other types as well.
  2519. """
  2520. cursor = "0"
  2521. while cursor != 0:
  2522. cursor, data = self.scan(
  2523. cursor=cursor, match=match, count=count, _type=_type, **kwargs
  2524. )
  2525. yield from data
  2526. def sscan(
  2527. self,
  2528. name: KeyT,
  2529. cursor: int = 0,
  2530. match: Union[PatternT, None] = None,
  2531. count: Union[int, None] = None,
  2532. ) -> ResponseT:
  2533. """
  2534. Incrementally return lists of elements in a set. Also return a cursor
  2535. indicating the scan position.
  2536. ``match`` allows for filtering the keys by pattern
  2537. ``count`` allows for hint the minimum number of returns
  2538. For more information see https://redis.io/commands/sscan
  2539. """
  2540. pieces: list[EncodableT] = [name, cursor]
  2541. if match is not None:
  2542. pieces.extend([b"MATCH", match])
  2543. if count is not None:
  2544. pieces.extend([b"COUNT", count])
  2545. return self.execute_command("SSCAN", *pieces)
  2546. def sscan_iter(
  2547. self,
  2548. name: KeyT,
  2549. match: Union[PatternT, None] = None,
  2550. count: Union[int, None] = None,
  2551. ) -> Iterator:
  2552. """
  2553. Make an iterator using the SSCAN command so that the client doesn't
  2554. need to remember the cursor position.
  2555. ``match`` allows for filtering the keys by pattern
  2556. ``count`` allows for hint the minimum number of returns
  2557. """
  2558. cursor = "0"
  2559. while cursor != 0:
  2560. cursor, data = self.sscan(name, cursor=cursor, match=match, count=count)
  2561. yield from data
  2562. def hscan(
  2563. self,
  2564. name: KeyT,
  2565. cursor: int = 0,
  2566. match: Union[PatternT, None] = None,
  2567. count: Union[int, None] = None,
  2568. no_values: Union[bool, None] = None,
  2569. ) -> ResponseT:
  2570. """
  2571. Incrementally return key/value slices in a hash. Also return a cursor
  2572. indicating the scan position.
  2573. ``match`` allows for filtering the keys by pattern
  2574. ``count`` allows for hint the minimum number of returns
  2575. ``no_values`` indicates to return only the keys, without values.
  2576. For more information see https://redis.io/commands/hscan
  2577. """
  2578. pieces: list[EncodableT] = [name, cursor]
  2579. if match is not None:
  2580. pieces.extend([b"MATCH", match])
  2581. if count is not None:
  2582. pieces.extend([b"COUNT", count])
  2583. if no_values is not None:
  2584. pieces.extend([b"NOVALUES"])
  2585. return self.execute_command("HSCAN", *pieces, no_values=no_values)
  2586. def hscan_iter(
  2587. self,
  2588. name: str,
  2589. match: Union[PatternT, None] = None,
  2590. count: Union[int, None] = None,
  2591. no_values: Union[bool, None] = None,
  2592. ) -> Iterator:
  2593. """
  2594. Make an iterator using the HSCAN command so that the client doesn't
  2595. need to remember the cursor position.
  2596. ``match`` allows for filtering the keys by pattern
  2597. ``count`` allows for hint the minimum number of returns
  2598. ``no_values`` indicates to return only the keys, without values
  2599. """
  2600. cursor = "0"
  2601. while cursor != 0:
  2602. cursor, data = self.hscan(
  2603. name, cursor=cursor, match=match, count=count, no_values=no_values
  2604. )
  2605. if no_values:
  2606. yield from data
  2607. else:
  2608. yield from data.items()
  2609. def zscan(
  2610. self,
  2611. name: KeyT,
  2612. cursor: int = 0,
  2613. match: Union[PatternT, None] = None,
  2614. count: Union[int, None] = None,
  2615. score_cast_func: Union[type, Callable] = float,
  2616. ) -> ResponseT:
  2617. """
  2618. Incrementally return lists of elements in a sorted set. Also return a
  2619. cursor indicating the scan position.
  2620. ``match`` allows for filtering the keys by pattern
  2621. ``count`` allows for hint the minimum number of returns
  2622. ``score_cast_func`` a callable used to cast the score return value
  2623. For more information see https://redis.io/commands/zscan
  2624. """
  2625. pieces = [name, cursor]
  2626. if match is not None:
  2627. pieces.extend([b"MATCH", match])
  2628. if count is not None:
  2629. pieces.extend([b"COUNT", count])
  2630. options = {"score_cast_func": score_cast_func}
  2631. return self.execute_command("ZSCAN", *pieces, **options)
  2632. def zscan_iter(
  2633. self,
  2634. name: KeyT,
  2635. match: Union[PatternT, None] = None,
  2636. count: Union[int, None] = None,
  2637. score_cast_func: Union[type, Callable] = float,
  2638. ) -> Iterator:
  2639. """
  2640. Make an iterator using the ZSCAN command so that the client doesn't
  2641. need to remember the cursor position.
  2642. ``match`` allows for filtering the keys by pattern
  2643. ``count`` allows for hint the minimum number of returns
  2644. ``score_cast_func`` a callable used to cast the score return value
  2645. """
  2646. cursor = "0"
  2647. while cursor != 0:
  2648. cursor, data = self.zscan(
  2649. name,
  2650. cursor=cursor,
  2651. match=match,
  2652. count=count,
  2653. score_cast_func=score_cast_func,
  2654. )
  2655. yield from data
  2656. class AsyncScanCommands(ScanCommands):
  2657. async def scan_iter(
  2658. self,
  2659. match: Union[PatternT, None] = None,
  2660. count: Union[int, None] = None,
  2661. _type: Union[str, None] = None,
  2662. **kwargs,
  2663. ) -> AsyncIterator:
  2664. """
  2665. Make an iterator using the SCAN command so that the client doesn't
  2666. need to remember the cursor position.
  2667. ``match`` allows for filtering the keys by pattern
  2668. ``count`` provides a hint to Redis about the number of keys to
  2669. return per batch.
  2670. ``_type`` filters the returned values by a particular Redis type.
  2671. Stock Redis instances allow for the following types:
  2672. HASH, LIST, SET, STREAM, STRING, ZSET
  2673. Additionally, Redis modules can expose other types as well.
  2674. """
  2675. cursor = "0"
  2676. while cursor != 0:
  2677. cursor, data = await self.scan(
  2678. cursor=cursor, match=match, count=count, _type=_type, **kwargs
  2679. )
  2680. for d in data:
  2681. yield d
  2682. async def sscan_iter(
  2683. self,
  2684. name: KeyT,
  2685. match: Union[PatternT, None] = None,
  2686. count: Union[int, None] = None,
  2687. ) -> AsyncIterator:
  2688. """
  2689. Make an iterator using the SSCAN command so that the client doesn't
  2690. need to remember the cursor position.
  2691. ``match`` allows for filtering the keys by pattern
  2692. ``count`` allows for hint the minimum number of returns
  2693. """
  2694. cursor = "0"
  2695. while cursor != 0:
  2696. cursor, data = await self.sscan(
  2697. name, cursor=cursor, match=match, count=count
  2698. )
  2699. for d in data:
  2700. yield d
  2701. async def hscan_iter(
  2702. self,
  2703. name: str,
  2704. match: Union[PatternT, None] = None,
  2705. count: Union[int, None] = None,
  2706. no_values: Union[bool, None] = None,
  2707. ) -> AsyncIterator:
  2708. """
  2709. Make an iterator using the HSCAN command so that the client doesn't
  2710. need to remember the cursor position.
  2711. ``match`` allows for filtering the keys by pattern
  2712. ``count`` allows for hint the minimum number of returns
  2713. ``no_values`` indicates to return only the keys, without values
  2714. """
  2715. cursor = "0"
  2716. while cursor != 0:
  2717. cursor, data = await self.hscan(
  2718. name, cursor=cursor, match=match, count=count, no_values=no_values
  2719. )
  2720. if no_values:
  2721. for it in data:
  2722. yield it
  2723. else:
  2724. for it in data.items():
  2725. yield it
  2726. async def zscan_iter(
  2727. self,
  2728. name: KeyT,
  2729. match: Union[PatternT, None] = None,
  2730. count: Union[int, None] = None,
  2731. score_cast_func: Union[type, Callable] = float,
  2732. ) -> AsyncIterator:
  2733. """
  2734. Make an iterator using the ZSCAN command so that the client doesn't
  2735. need to remember the cursor position.
  2736. ``match`` allows for filtering the keys by pattern
  2737. ``count`` allows for hint the minimum number of returns
  2738. ``score_cast_func`` a callable used to cast the score return value
  2739. """
  2740. cursor = "0"
  2741. while cursor != 0:
  2742. cursor, data = await self.zscan(
  2743. name,
  2744. cursor=cursor,
  2745. match=match,
  2746. count=count,
  2747. score_cast_func=score_cast_func,
  2748. )
  2749. for d in data:
  2750. yield d
  2751. class SetCommands(CommandsProtocol):
  2752. """
  2753. Redis commands for Set data type.
  2754. see: https://redis.io/topics/data-types#sets
  2755. """
  2756. def sadd(self, name: str, *values: FieldT) -> Union[Awaitable[int], int]:
  2757. """
  2758. Add ``value(s)`` to set ``name``
  2759. For more information see https://redis.io/commands/sadd
  2760. """
  2761. return self.execute_command("SADD", name, *values)
  2762. def scard(self, name: str) -> Union[Awaitable[int], int]:
  2763. """
  2764. Return the number of elements in set ``name``
  2765. For more information see https://redis.io/commands/scard
  2766. """
  2767. return self.execute_command("SCARD", name)
  2768. def sdiff(self, keys: List, *args: List) -> Union[Awaitable[list], list]:
  2769. """
  2770. Return the difference of sets specified by ``keys``
  2771. For more information see https://redis.io/commands/sdiff
  2772. """
  2773. args = list_or_args(keys, args)
  2774. return self.execute_command("SDIFF", *args)
  2775. def sdiffstore(
  2776. self, dest: str, keys: List, *args: List
  2777. ) -> Union[Awaitable[int], int]:
  2778. """
  2779. Store the difference of sets specified by ``keys`` into a new
  2780. set named ``dest``. Returns the number of keys in the new set.
  2781. For more information see https://redis.io/commands/sdiffstore
  2782. """
  2783. args = list_or_args(keys, args)
  2784. return self.execute_command("SDIFFSTORE", dest, *args)
  2785. def sinter(self, keys: List, *args: List) -> Union[Awaitable[list], list]:
  2786. """
  2787. Return the intersection of sets specified by ``keys``
  2788. For more information see https://redis.io/commands/sinter
  2789. """
  2790. args = list_or_args(keys, args)
  2791. return self.execute_command("SINTER", *args)
  2792. def sintercard(
  2793. self, numkeys: int, keys: List[str], limit: int = 0
  2794. ) -> Union[Awaitable[int], int]:
  2795. """
  2796. Return the cardinality of the intersect of multiple sets specified by ``keys`.
  2797. When LIMIT provided (defaults to 0 and means unlimited), if the intersection
  2798. cardinality reaches limit partway through the computation, the algorithm will
  2799. exit and yield limit as the cardinality
  2800. For more information see https://redis.io/commands/sintercard
  2801. """
  2802. args = [numkeys, *keys, "LIMIT", limit]
  2803. return self.execute_command("SINTERCARD", *args)
  2804. def sinterstore(
  2805. self, dest: str, keys: List, *args: List
  2806. ) -> Union[Awaitable[int], int]:
  2807. """
  2808. Store the intersection of sets specified by ``keys`` into a new
  2809. set named ``dest``. Returns the number of keys in the new set.
  2810. For more information see https://redis.io/commands/sinterstore
  2811. """
  2812. args = list_or_args(keys, args)
  2813. return self.execute_command("SINTERSTORE", dest, *args)
  2814. def sismember(
  2815. self, name: str, value: str
  2816. ) -> Union[Awaitable[Union[Literal[0], Literal[1]]], Union[Literal[0], Literal[1]]]:
  2817. """
  2818. Return whether ``value`` is a member of set ``name``:
  2819. - 1 if the value is a member of the set.
  2820. - 0 if the value is not a member of the set or if key does not exist.
  2821. For more information see https://redis.io/commands/sismember
  2822. """
  2823. return self.execute_command("SISMEMBER", name, value)
  2824. def smembers(self, name: str) -> Union[Awaitable[Set], Set]:
  2825. """
  2826. Return all members of the set ``name``
  2827. For more information see https://redis.io/commands/smembers
  2828. """
  2829. return self.execute_command("SMEMBERS", name)
  2830. def smismember(
  2831. self, name: str, values: List, *args: List
  2832. ) -> Union[
  2833. Awaitable[List[Union[Literal[0], Literal[1]]]],
  2834. List[Union[Literal[0], Literal[1]]],
  2835. ]:
  2836. """
  2837. Return whether each value in ``values`` is a member of the set ``name``
  2838. as a list of ``int`` in the order of ``values``:
  2839. - 1 if the value is a member of the set.
  2840. - 0 if the value is not a member of the set or if key does not exist.
  2841. For more information see https://redis.io/commands/smismember
  2842. """
  2843. args = list_or_args(values, args)
  2844. return self.execute_command("SMISMEMBER", name, *args)
  2845. def smove(self, src: str, dst: str, value: str) -> Union[Awaitable[bool], bool]:
  2846. """
  2847. Move ``value`` from set ``src`` to set ``dst`` atomically
  2848. For more information see https://redis.io/commands/smove
  2849. """
  2850. return self.execute_command("SMOVE", src, dst, value)
  2851. def spop(self, name: str, count: Optional[int] = None) -> Union[str, List, None]:
  2852. """
  2853. Remove and return a random member of set ``name``
  2854. For more information see https://redis.io/commands/spop
  2855. """
  2856. args = (count is not None) and [count] or []
  2857. return self.execute_command("SPOP", name, *args)
  2858. def srandmember(
  2859. self, name: str, number: Optional[int] = None
  2860. ) -> Union[str, List, None]:
  2861. """
  2862. If ``number`` is None, returns a random member of set ``name``.
  2863. If ``number`` is supplied, returns a list of ``number`` random
  2864. members of set ``name``. Note this is only available when running
  2865. Redis 2.6+.
  2866. For more information see https://redis.io/commands/srandmember
  2867. """
  2868. args = (number is not None) and [number] or []
  2869. return self.execute_command("SRANDMEMBER", name, *args)
  2870. def srem(self, name: str, *values: FieldT) -> Union[Awaitable[int], int]:
  2871. """
  2872. Remove ``values`` from set ``name``
  2873. For more information see https://redis.io/commands/srem
  2874. """
  2875. return self.execute_command("SREM", name, *values)
  2876. def sunion(self, keys: List, *args: List) -> Union[Awaitable[List], List]:
  2877. """
  2878. Return the union of sets specified by ``keys``
  2879. For more information see https://redis.io/commands/sunion
  2880. """
  2881. args = list_or_args(keys, args)
  2882. return self.execute_command("SUNION", *args)
  2883. def sunionstore(
  2884. self, dest: str, keys: List, *args: List
  2885. ) -> Union[Awaitable[int], int]:
  2886. """
  2887. Store the union of sets specified by ``keys`` into a new
  2888. set named ``dest``. Returns the number of keys in the new set.
  2889. For more information see https://redis.io/commands/sunionstore
  2890. """
  2891. args = list_or_args(keys, args)
  2892. return self.execute_command("SUNIONSTORE", dest, *args)
  2893. AsyncSetCommands = SetCommands
  2894. class StreamCommands(CommandsProtocol):
  2895. """
  2896. Redis commands for Stream data type.
  2897. see: https://redis.io/topics/streams-intro
  2898. """
  2899. def xack(self, name: KeyT, groupname: GroupT, *ids: StreamIdT) -> ResponseT:
  2900. """
  2901. Acknowledges the successful processing of one or more messages.
  2902. name: name of the stream.
  2903. groupname: name of the consumer group.
  2904. *ids: message ids to acknowledge.
  2905. For more information see https://redis.io/commands/xack
  2906. """
  2907. return self.execute_command("XACK", name, groupname, *ids)
  2908. def xadd(
  2909. self,
  2910. name: KeyT,
  2911. fields: Dict[FieldT, EncodableT],
  2912. id: StreamIdT = "*",
  2913. maxlen: Union[int, None] = None,
  2914. approximate: bool = True,
  2915. nomkstream: bool = False,
  2916. minid: Union[StreamIdT, None] = None,
  2917. limit: Union[int, None] = None,
  2918. ) -> ResponseT:
  2919. """
  2920. Add to a stream.
  2921. name: name of the stream
  2922. fields: dict of field/value pairs to insert into the stream
  2923. id: Location to insert this record. By default it is appended.
  2924. maxlen: truncate old stream members beyond this size.
  2925. Can't be specified with minid.
  2926. approximate: actual stream length may be slightly more than maxlen
  2927. nomkstream: When set to true, do not make a stream
  2928. minid: the minimum id in the stream to query.
  2929. Can't be specified with maxlen.
  2930. limit: specifies the maximum number of entries to retrieve
  2931. For more information see https://redis.io/commands/xadd
  2932. """
  2933. pieces: list[EncodableT] = []
  2934. if maxlen is not None and minid is not None:
  2935. raise DataError("Only one of ```maxlen``` or ```minid``` may be specified")
  2936. if maxlen is not None:
  2937. if not isinstance(maxlen, int) or maxlen < 0:
  2938. raise DataError("XADD maxlen must be non-negative integer")
  2939. pieces.append(b"MAXLEN")
  2940. if approximate:
  2941. pieces.append(b"~")
  2942. pieces.append(str(maxlen))
  2943. if minid is not None:
  2944. pieces.append(b"MINID")
  2945. if approximate:
  2946. pieces.append(b"~")
  2947. pieces.append(minid)
  2948. if limit is not None:
  2949. pieces.extend([b"LIMIT", limit])
  2950. if nomkstream:
  2951. pieces.append(b"NOMKSTREAM")
  2952. pieces.append(id)
  2953. if not isinstance(fields, dict) or len(fields) == 0:
  2954. raise DataError("XADD fields must be a non-empty dict")
  2955. for pair in fields.items():
  2956. pieces.extend(pair)
  2957. return self.execute_command("XADD", name, *pieces)
  2958. def xautoclaim(
  2959. self,
  2960. name: KeyT,
  2961. groupname: GroupT,
  2962. consumername: ConsumerT,
  2963. min_idle_time: int,
  2964. start_id: StreamIdT = "0-0",
  2965. count: Union[int, None] = None,
  2966. justid: bool = False,
  2967. ) -> ResponseT:
  2968. """
  2969. Transfers ownership of pending stream entries that match the specified
  2970. criteria. Conceptually, equivalent to calling XPENDING and then XCLAIM,
  2971. but provides a more straightforward way to deal with message delivery
  2972. failures via SCAN-like semantics.
  2973. name: name of the stream.
  2974. groupname: name of the consumer group.
  2975. consumername: name of a consumer that claims the message.
  2976. min_idle_time: filter messages that were idle less than this amount of
  2977. milliseconds.
  2978. start_id: filter messages with equal or greater ID.
  2979. count: optional integer, upper limit of the number of entries that the
  2980. command attempts to claim. Set to 100 by default.
  2981. justid: optional boolean, false by default. Return just an array of IDs
  2982. of messages successfully claimed, without returning the actual message
  2983. For more information see https://redis.io/commands/xautoclaim
  2984. """
  2985. try:
  2986. if int(min_idle_time) < 0:
  2987. raise DataError(
  2988. "XAUTOCLAIM min_idle_time must be a nonnegative integer"
  2989. )
  2990. except TypeError:
  2991. pass
  2992. kwargs = {}
  2993. pieces = [name, groupname, consumername, min_idle_time, start_id]
  2994. try:
  2995. if int(count) < 0:
  2996. raise DataError("XPENDING count must be a integer >= 0")
  2997. pieces.extend([b"COUNT", count])
  2998. except TypeError:
  2999. pass
  3000. if justid:
  3001. pieces.append(b"JUSTID")
  3002. kwargs["parse_justid"] = True
  3003. return self.execute_command("XAUTOCLAIM", *pieces, **kwargs)
  3004. def xclaim(
  3005. self,
  3006. name: KeyT,
  3007. groupname: GroupT,
  3008. consumername: ConsumerT,
  3009. min_idle_time: int,
  3010. message_ids: Union[List[StreamIdT], Tuple[StreamIdT]],
  3011. idle: Union[int, None] = None,
  3012. time: Union[int, None] = None,
  3013. retrycount: Union[int, None] = None,
  3014. force: bool = False,
  3015. justid: bool = False,
  3016. ) -> ResponseT:
  3017. """
  3018. Changes the ownership of a pending message.
  3019. name: name of the stream.
  3020. groupname: name of the consumer group.
  3021. consumername: name of a consumer that claims the message.
  3022. min_idle_time: filter messages that were idle less than this amount of
  3023. milliseconds
  3024. message_ids: non-empty list or tuple of message IDs to claim
  3025. idle: optional. Set the idle time (last time it was delivered) of the
  3026. message in ms
  3027. time: optional integer. This is the same as idle but instead of a
  3028. relative amount of milliseconds, it sets the idle time to a specific
  3029. Unix time (in milliseconds).
  3030. retrycount: optional integer. set the retry counter to the specified
  3031. value. This counter is incremented every time a message is delivered
  3032. again.
  3033. force: optional boolean, false by default. Creates the pending message
  3034. entry in the PEL even if certain specified IDs are not already in the
  3035. PEL assigned to a different client.
  3036. justid: optional boolean, false by default. Return just an array of IDs
  3037. of messages successfully claimed, without returning the actual message
  3038. For more information see https://redis.io/commands/xclaim
  3039. """
  3040. if not isinstance(min_idle_time, int) or min_idle_time < 0:
  3041. raise DataError("XCLAIM min_idle_time must be a non negative integer")
  3042. if not isinstance(message_ids, (list, tuple)) or not message_ids:
  3043. raise DataError(
  3044. "XCLAIM message_ids must be a non empty list or "
  3045. "tuple of message IDs to claim"
  3046. )
  3047. kwargs = {}
  3048. pieces: list[EncodableT] = [name, groupname, consumername, str(min_idle_time)]
  3049. pieces.extend(list(message_ids))
  3050. if idle is not None:
  3051. if not isinstance(idle, int):
  3052. raise DataError("XCLAIM idle must be an integer")
  3053. pieces.extend((b"IDLE", str(idle)))
  3054. if time is not None:
  3055. if not isinstance(time, int):
  3056. raise DataError("XCLAIM time must be an integer")
  3057. pieces.extend((b"TIME", str(time)))
  3058. if retrycount is not None:
  3059. if not isinstance(retrycount, int):
  3060. raise DataError("XCLAIM retrycount must be an integer")
  3061. pieces.extend((b"RETRYCOUNT", str(retrycount)))
  3062. if force:
  3063. if not isinstance(force, bool):
  3064. raise DataError("XCLAIM force must be a boolean")
  3065. pieces.append(b"FORCE")
  3066. if justid:
  3067. if not isinstance(justid, bool):
  3068. raise DataError("XCLAIM justid must be a boolean")
  3069. pieces.append(b"JUSTID")
  3070. kwargs["parse_justid"] = True
  3071. return self.execute_command("XCLAIM", *pieces, **kwargs)
  3072. def xdel(self, name: KeyT, *ids: StreamIdT) -> ResponseT:
  3073. """
  3074. Deletes one or more messages from a stream.
  3075. name: name of the stream.
  3076. *ids: message ids to delete.
  3077. For more information see https://redis.io/commands/xdel
  3078. """
  3079. return self.execute_command("XDEL", name, *ids)
  3080. def xgroup_create(
  3081. self,
  3082. name: KeyT,
  3083. groupname: GroupT,
  3084. id: StreamIdT = "$",
  3085. mkstream: bool = False,
  3086. entries_read: Optional[int] = None,
  3087. ) -> ResponseT:
  3088. """
  3089. Create a new consumer group associated with a stream.
  3090. name: name of the stream.
  3091. groupname: name of the consumer group.
  3092. id: ID of the last item in the stream to consider already delivered.
  3093. For more information see https://redis.io/commands/xgroup-create
  3094. """
  3095. pieces: list[EncodableT] = ["XGROUP CREATE", name, groupname, id]
  3096. if mkstream:
  3097. pieces.append(b"MKSTREAM")
  3098. if entries_read is not None:
  3099. pieces.extend(["ENTRIESREAD", entries_read])
  3100. return self.execute_command(*pieces)
  3101. def xgroup_delconsumer(
  3102. self, name: KeyT, groupname: GroupT, consumername: ConsumerT
  3103. ) -> ResponseT:
  3104. """
  3105. Remove a specific consumer from a consumer group.
  3106. Returns the number of pending messages that the consumer had before it
  3107. was deleted.
  3108. name: name of the stream.
  3109. groupname: name of the consumer group.
  3110. consumername: name of consumer to delete
  3111. For more information see https://redis.io/commands/xgroup-delconsumer
  3112. """
  3113. return self.execute_command("XGROUP DELCONSUMER", name, groupname, consumername)
  3114. def xgroup_destroy(self, name: KeyT, groupname: GroupT) -> ResponseT:
  3115. """
  3116. Destroy a consumer group.
  3117. name: name of the stream.
  3118. groupname: name of the consumer group.
  3119. For more information see https://redis.io/commands/xgroup-destroy
  3120. """
  3121. return self.execute_command("XGROUP DESTROY", name, groupname)
  3122. def xgroup_createconsumer(
  3123. self, name: KeyT, groupname: GroupT, consumername: ConsumerT
  3124. ) -> ResponseT:
  3125. """
  3126. Consumers in a consumer group are auto-created every time a new
  3127. consumer name is mentioned by some command.
  3128. They can be explicitly created by using this command.
  3129. name: name of the stream.
  3130. groupname: name of the consumer group.
  3131. consumername: name of consumer to create.
  3132. See: https://redis.io/commands/xgroup-createconsumer
  3133. """
  3134. return self.execute_command(
  3135. "XGROUP CREATECONSUMER", name, groupname, consumername
  3136. )
  3137. def xgroup_setid(
  3138. self,
  3139. name: KeyT,
  3140. groupname: GroupT,
  3141. id: StreamIdT,
  3142. entries_read: Optional[int] = None,
  3143. ) -> ResponseT:
  3144. """
  3145. Set the consumer group last delivered ID to something else.
  3146. name: name of the stream.
  3147. groupname: name of the consumer group.
  3148. id: ID of the last item in the stream to consider already delivered.
  3149. For more information see https://redis.io/commands/xgroup-setid
  3150. """
  3151. pieces = [name, groupname, id]
  3152. if entries_read is not None:
  3153. pieces.extend(["ENTRIESREAD", entries_read])
  3154. return self.execute_command("XGROUP SETID", *pieces)
  3155. def xinfo_consumers(self, name: KeyT, groupname: GroupT) -> ResponseT:
  3156. """
  3157. Returns general information about the consumers in the group.
  3158. name: name of the stream.
  3159. groupname: name of the consumer group.
  3160. For more information see https://redis.io/commands/xinfo-consumers
  3161. """
  3162. return self.execute_command("XINFO CONSUMERS", name, groupname)
  3163. def xinfo_groups(self, name: KeyT) -> ResponseT:
  3164. """
  3165. Returns general information about the consumer groups of the stream.
  3166. name: name of the stream.
  3167. For more information see https://redis.io/commands/xinfo-groups
  3168. """
  3169. return self.execute_command("XINFO GROUPS", name)
  3170. def xinfo_stream(self, name: KeyT, full: bool = False) -> ResponseT:
  3171. """
  3172. Returns general information about the stream.
  3173. name: name of the stream.
  3174. full: optional boolean, false by default. Return full summary
  3175. For more information see https://redis.io/commands/xinfo-stream
  3176. """
  3177. pieces = [name]
  3178. options = {}
  3179. if full:
  3180. pieces.append(b"FULL")
  3181. options = {"full": full}
  3182. return self.execute_command("XINFO STREAM", *pieces, **options)
  3183. def xlen(self, name: KeyT) -> ResponseT:
  3184. """
  3185. Returns the number of elements in a given stream.
  3186. For more information see https://redis.io/commands/xlen
  3187. """
  3188. return self.execute_command("XLEN", name)
  3189. def xpending(self, name: KeyT, groupname: GroupT) -> ResponseT:
  3190. """
  3191. Returns information about pending messages of a group.
  3192. name: name of the stream.
  3193. groupname: name of the consumer group.
  3194. For more information see https://redis.io/commands/xpending
  3195. """
  3196. return self.execute_command("XPENDING", name, groupname)
  3197. def xpending_range(
  3198. self,
  3199. name: KeyT,
  3200. groupname: GroupT,
  3201. min: StreamIdT,
  3202. max: StreamIdT,
  3203. count: int,
  3204. consumername: Union[ConsumerT, None] = None,
  3205. idle: Union[int, None] = None,
  3206. ) -> ResponseT:
  3207. """
  3208. Returns information about pending messages, in a range.
  3209. name: name of the stream.
  3210. groupname: name of the consumer group.
  3211. idle: available from version 6.2. filter entries by their
  3212. idle-time, given in milliseconds (optional).
  3213. min: minimum stream ID.
  3214. max: maximum stream ID.
  3215. count: number of messages to return
  3216. consumername: name of a consumer to filter by (optional).
  3217. """
  3218. if {min, max, count} == {None}:
  3219. if idle is not None or consumername is not None:
  3220. raise DataError(
  3221. "if XPENDING is provided with idle time"
  3222. " or consumername, it must be provided"
  3223. " with min, max and count parameters"
  3224. )
  3225. return self.xpending(name, groupname)
  3226. pieces = [name, groupname]
  3227. if min is None or max is None or count is None:
  3228. raise DataError(
  3229. "XPENDING must be provided with min, max "
  3230. "and count parameters, or none of them."
  3231. )
  3232. # idle
  3233. try:
  3234. if int(idle) < 0:
  3235. raise DataError("XPENDING idle must be a integer >= 0")
  3236. pieces.extend(["IDLE", idle])
  3237. except TypeError:
  3238. pass
  3239. # count
  3240. try:
  3241. if int(count) < 0:
  3242. raise DataError("XPENDING count must be a integer >= 0")
  3243. pieces.extend([min, max, count])
  3244. except TypeError:
  3245. pass
  3246. # consumername
  3247. if consumername:
  3248. pieces.append(consumername)
  3249. return self.execute_command("XPENDING", *pieces, parse_detail=True)
  3250. def xrange(
  3251. self,
  3252. name: KeyT,
  3253. min: StreamIdT = "-",
  3254. max: StreamIdT = "+",
  3255. count: Union[int, None] = None,
  3256. ) -> ResponseT:
  3257. """
  3258. Read stream values within an interval.
  3259. name: name of the stream.
  3260. start: first stream ID. defaults to '-',
  3261. meaning the earliest available.
  3262. finish: last stream ID. defaults to '+',
  3263. meaning the latest available.
  3264. count: if set, only return this many items, beginning with the
  3265. earliest available.
  3266. For more information see https://redis.io/commands/xrange
  3267. """
  3268. pieces = [min, max]
  3269. if count is not None:
  3270. if not isinstance(count, int) or count < 1:
  3271. raise DataError("XRANGE count must be a positive integer")
  3272. pieces.append(b"COUNT")
  3273. pieces.append(str(count))
  3274. return self.execute_command("XRANGE", name, *pieces)
  3275. def xread(
  3276. self,
  3277. streams: Dict[KeyT, StreamIdT],
  3278. count: Union[int, None] = None,
  3279. block: Union[int, None] = None,
  3280. ) -> ResponseT:
  3281. """
  3282. Block and monitor multiple streams for new data.
  3283. streams: a dict of stream names to stream IDs, where
  3284. IDs indicate the last ID already seen.
  3285. count: if set, only return this many items, beginning with the
  3286. earliest available.
  3287. block: number of milliseconds to wait, if nothing already present.
  3288. For more information see https://redis.io/commands/xread
  3289. """
  3290. pieces = []
  3291. if block is not None:
  3292. if not isinstance(block, int) or block < 0:
  3293. raise DataError("XREAD block must be a non-negative integer")
  3294. pieces.append(b"BLOCK")
  3295. pieces.append(str(block))
  3296. if count is not None:
  3297. if not isinstance(count, int) or count < 1:
  3298. raise DataError("XREAD count must be a positive integer")
  3299. pieces.append(b"COUNT")
  3300. pieces.append(str(count))
  3301. if not isinstance(streams, dict) or len(streams) == 0:
  3302. raise DataError("XREAD streams must be a non empty dict")
  3303. pieces.append(b"STREAMS")
  3304. keys, values = zip(*streams.items())
  3305. pieces.extend(keys)
  3306. pieces.extend(values)
  3307. return self.execute_command("XREAD", *pieces)
  3308. def xreadgroup(
  3309. self,
  3310. groupname: str,
  3311. consumername: str,
  3312. streams: Dict[KeyT, StreamIdT],
  3313. count: Union[int, None] = None,
  3314. block: Union[int, None] = None,
  3315. noack: bool = False,
  3316. ) -> ResponseT:
  3317. """
  3318. Read from a stream via a consumer group.
  3319. groupname: name of the consumer group.
  3320. consumername: name of the requesting consumer.
  3321. streams: a dict of stream names to stream IDs, where
  3322. IDs indicate the last ID already seen.
  3323. count: if set, only return this many items, beginning with the
  3324. earliest available.
  3325. block: number of milliseconds to wait, if nothing already present.
  3326. noack: do not add messages to the PEL
  3327. For more information see https://redis.io/commands/xreadgroup
  3328. """
  3329. pieces: list[EncodableT] = [b"GROUP", groupname, consumername]
  3330. if count is not None:
  3331. if not isinstance(count, int) or count < 1:
  3332. raise DataError("XREADGROUP count must be a positive integer")
  3333. pieces.append(b"COUNT")
  3334. pieces.append(str(count))
  3335. if block is not None:
  3336. if not isinstance(block, int) or block < 0:
  3337. raise DataError("XREADGROUP block must be a non-negative integer")
  3338. pieces.append(b"BLOCK")
  3339. pieces.append(str(block))
  3340. if noack:
  3341. pieces.append(b"NOACK")
  3342. if not isinstance(streams, dict) or len(streams) == 0:
  3343. raise DataError("XREADGROUP streams must be a non empty dict")
  3344. pieces.append(b"STREAMS")
  3345. pieces.extend(streams.keys())
  3346. pieces.extend(streams.values())
  3347. return self.execute_command("XREADGROUP", *pieces)
  3348. def xrevrange(
  3349. self,
  3350. name: KeyT,
  3351. max: StreamIdT = "+",
  3352. min: StreamIdT = "-",
  3353. count: Union[int, None] = None,
  3354. ) -> ResponseT:
  3355. """
  3356. Read stream values within an interval, in reverse order.
  3357. name: name of the stream
  3358. start: first stream ID. defaults to '+',
  3359. meaning the latest available.
  3360. finish: last stream ID. defaults to '-',
  3361. meaning the earliest available.
  3362. count: if set, only return this many items, beginning with the
  3363. latest available.
  3364. For more information see https://redis.io/commands/xrevrange
  3365. """
  3366. pieces: list[EncodableT] = [max, min]
  3367. if count is not None:
  3368. if not isinstance(count, int) or count < 1:
  3369. raise DataError("XREVRANGE count must be a positive integer")
  3370. pieces.append(b"COUNT")
  3371. pieces.append(str(count))
  3372. return self.execute_command("XREVRANGE", name, *pieces)
  3373. def xtrim(
  3374. self,
  3375. name: KeyT,
  3376. maxlen: Union[int, None] = None,
  3377. approximate: bool = True,
  3378. minid: Union[StreamIdT, None] = None,
  3379. limit: Union[int, None] = None,
  3380. ) -> ResponseT:
  3381. """
  3382. Trims old messages from a stream.
  3383. name: name of the stream.
  3384. maxlen: truncate old stream messages beyond this size
  3385. Can't be specified with minid.
  3386. approximate: actual stream length may be slightly more than maxlen
  3387. minid: the minimum id in the stream to query
  3388. Can't be specified with maxlen.
  3389. limit: specifies the maximum number of entries to retrieve
  3390. For more information see https://redis.io/commands/xtrim
  3391. """
  3392. pieces: list[EncodableT] = []
  3393. if maxlen is not None and minid is not None:
  3394. raise DataError("Only one of ``maxlen`` or ``minid`` may be specified")
  3395. if maxlen is None and minid is None:
  3396. raise DataError("One of ``maxlen`` or ``minid`` must be specified")
  3397. if maxlen is not None:
  3398. pieces.append(b"MAXLEN")
  3399. if minid is not None:
  3400. pieces.append(b"MINID")
  3401. if approximate:
  3402. pieces.append(b"~")
  3403. if maxlen is not None:
  3404. pieces.append(maxlen)
  3405. if minid is not None:
  3406. pieces.append(minid)
  3407. if limit is not None:
  3408. pieces.append(b"LIMIT")
  3409. pieces.append(limit)
  3410. return self.execute_command("XTRIM", name, *pieces)
  3411. AsyncStreamCommands = StreamCommands
  3412. class SortedSetCommands(CommandsProtocol):
  3413. """
  3414. Redis commands for Sorted Sets data type.
  3415. see: https://redis.io/topics/data-types-intro#redis-sorted-sets
  3416. """
  3417. def zadd(
  3418. self,
  3419. name: KeyT,
  3420. mapping: Mapping[AnyKeyT, EncodableT],
  3421. nx: bool = False,
  3422. xx: bool = False,
  3423. ch: bool = False,
  3424. incr: bool = False,
  3425. gt: bool = False,
  3426. lt: bool = False,
  3427. ) -> ResponseT:
  3428. """
  3429. Set any number of element-name, score pairs to the key ``name``. Pairs
  3430. are specified as a dict of element-names keys to score values.
  3431. ``nx`` forces ZADD to only create new elements and not to update
  3432. scores for elements that already exist.
  3433. ``xx`` forces ZADD to only update scores of elements that already
  3434. exist. New elements will not be added.
  3435. ``ch`` modifies the return value to be the numbers of elements changed.
  3436. Changed elements include new elements that were added and elements
  3437. whose scores changed.
  3438. ``incr`` modifies ZADD to behave like ZINCRBY. In this mode only a
  3439. single element/score pair can be specified and the score is the amount
  3440. the existing score will be incremented by. When using this mode the
  3441. return value of ZADD will be the new score of the element.
  3442. ``LT`` Only update existing elements if the new score is less than
  3443. the current score. This flag doesn't prevent adding new elements.
  3444. ``GT`` Only update existing elements if the new score is greater than
  3445. the current score. This flag doesn't prevent adding new elements.
  3446. The return value of ZADD varies based on the mode specified. With no
  3447. options, ZADD returns the number of new elements added to the sorted
  3448. set.
  3449. ``NX``, ``LT``, and ``GT`` are mutually exclusive options.
  3450. See: https://redis.io/commands/ZADD
  3451. """
  3452. if not mapping:
  3453. raise DataError("ZADD requires at least one element/score pair")
  3454. if nx and xx:
  3455. raise DataError("ZADD allows either 'nx' or 'xx', not both")
  3456. if gt and lt:
  3457. raise DataError("ZADD allows either 'gt' or 'lt', not both")
  3458. if incr and len(mapping) != 1:
  3459. raise DataError(
  3460. "ZADD option 'incr' only works when passing a "
  3461. "single element/score pair"
  3462. )
  3463. if nx and (gt or lt):
  3464. raise DataError("Only one of 'nx', 'lt', or 'gr' may be defined.")
  3465. pieces: list[EncodableT] = []
  3466. options = {}
  3467. if nx:
  3468. pieces.append(b"NX")
  3469. if xx:
  3470. pieces.append(b"XX")
  3471. if ch:
  3472. pieces.append(b"CH")
  3473. if incr:
  3474. pieces.append(b"INCR")
  3475. options["as_score"] = True
  3476. if gt:
  3477. pieces.append(b"GT")
  3478. if lt:
  3479. pieces.append(b"LT")
  3480. for pair in mapping.items():
  3481. pieces.append(pair[1])
  3482. pieces.append(pair[0])
  3483. return self.execute_command("ZADD", name, *pieces, **options)
  3484. def zcard(self, name: KeyT) -> ResponseT:
  3485. """
  3486. Return the number of elements in the sorted set ``name``
  3487. For more information see https://redis.io/commands/zcard
  3488. """
  3489. return self.execute_command("ZCARD", name)
  3490. def zcount(self, name: KeyT, min: ZScoreBoundT, max: ZScoreBoundT) -> ResponseT:
  3491. """
  3492. Returns the number of elements in the sorted set at key ``name`` with
  3493. a score between ``min`` and ``max``.
  3494. For more information see https://redis.io/commands/zcount
  3495. """
  3496. return self.execute_command("ZCOUNT", name, min, max)
  3497. def zdiff(self, keys: KeysT, withscores: bool = False) -> ResponseT:
  3498. """
  3499. Returns the difference between the first and all successive input
  3500. sorted sets provided in ``keys``.
  3501. For more information see https://redis.io/commands/zdiff
  3502. """
  3503. pieces = [len(keys), *keys]
  3504. if withscores:
  3505. pieces.append("WITHSCORES")
  3506. return self.execute_command("ZDIFF", *pieces)
  3507. def zdiffstore(self, dest: KeyT, keys: KeysT) -> ResponseT:
  3508. """
  3509. Computes the difference between the first and all successive input
  3510. sorted sets provided in ``keys`` and stores the result in ``dest``.
  3511. For more information see https://redis.io/commands/zdiffstore
  3512. """
  3513. pieces = [len(keys), *keys]
  3514. return self.execute_command("ZDIFFSTORE", dest, *pieces)
  3515. def zincrby(self, name: KeyT, amount: float, value: EncodableT) -> ResponseT:
  3516. """
  3517. Increment the score of ``value`` in sorted set ``name`` by ``amount``
  3518. For more information see https://redis.io/commands/zincrby
  3519. """
  3520. return self.execute_command("ZINCRBY", name, amount, value)
  3521. def zinter(
  3522. self, keys: KeysT, aggregate: Union[str, None] = None, withscores: bool = False
  3523. ) -> ResponseT:
  3524. """
  3525. Return the intersect of multiple sorted sets specified by ``keys``.
  3526. With the ``aggregate`` option, it is possible to specify how the
  3527. results of the union are aggregated. This option defaults to SUM,
  3528. where the score of an element is summed across the inputs where it
  3529. exists. When this option is set to either MIN or MAX, the resulting
  3530. set will contain the minimum or maximum score of an element across
  3531. the inputs where it exists.
  3532. For more information see https://redis.io/commands/zinter
  3533. """
  3534. return self._zaggregate("ZINTER", None, keys, aggregate, withscores=withscores)
  3535. def zinterstore(
  3536. self,
  3537. dest: KeyT,
  3538. keys: Union[Sequence[KeyT], Mapping[AnyKeyT, float]],
  3539. aggregate: Union[str, None] = None,
  3540. ) -> ResponseT:
  3541. """
  3542. Intersect multiple sorted sets specified by ``keys`` into a new
  3543. sorted set, ``dest``. Scores in the destination will be aggregated
  3544. based on the ``aggregate``. This option defaults to SUM, where the
  3545. score of an element is summed across the inputs where it exists.
  3546. When this option is set to either MIN or MAX, the resulting set will
  3547. contain the minimum or maximum score of an element across the inputs
  3548. where it exists.
  3549. For more information see https://redis.io/commands/zinterstore
  3550. """
  3551. return self._zaggregate("ZINTERSTORE", dest, keys, aggregate)
  3552. def zintercard(
  3553. self, numkeys: int, keys: List[str], limit: int = 0
  3554. ) -> Union[Awaitable[int], int]:
  3555. """
  3556. Return the cardinality of the intersect of multiple sorted sets
  3557. specified by ``keys`.
  3558. When LIMIT provided (defaults to 0 and means unlimited), if the intersection
  3559. cardinality reaches limit partway through the computation, the algorithm will
  3560. exit and yield limit as the cardinality
  3561. For more information see https://redis.io/commands/zintercard
  3562. """
  3563. args = [numkeys, *keys, "LIMIT", limit]
  3564. return self.execute_command("ZINTERCARD", *args)
  3565. def zlexcount(self, name, min, max):
  3566. """
  3567. Return the number of items in the sorted set ``name`` between the
  3568. lexicographical range ``min`` and ``max``.
  3569. For more information see https://redis.io/commands/zlexcount
  3570. """
  3571. return self.execute_command("ZLEXCOUNT", name, min, max)
  3572. def zpopmax(self, name: KeyT, count: Union[int, None] = None) -> ResponseT:
  3573. """
  3574. Remove and return up to ``count`` members with the highest scores
  3575. from the sorted set ``name``.
  3576. For more information see https://redis.io/commands/zpopmax
  3577. """
  3578. args = (count is not None) and [count] or []
  3579. options = {"withscores": True}
  3580. return self.execute_command("ZPOPMAX", name, *args, **options)
  3581. def zpopmin(self, name: KeyT, count: Union[int, None] = None) -> ResponseT:
  3582. """
  3583. Remove and return up to ``count`` members with the lowest scores
  3584. from the sorted set ``name``.
  3585. For more information see https://redis.io/commands/zpopmin
  3586. """
  3587. args = (count is not None) and [count] or []
  3588. options = {"withscores": True}
  3589. return self.execute_command("ZPOPMIN", name, *args, **options)
  3590. def zrandmember(
  3591. self, key: KeyT, count: int = None, withscores: bool = False
  3592. ) -> ResponseT:
  3593. """
  3594. Return a random element from the sorted set value stored at key.
  3595. ``count`` if the argument is positive, return an array of distinct
  3596. fields. If called with a negative count, the behavior changes and
  3597. the command is allowed to return the same field multiple times.
  3598. In this case, the number of returned fields is the absolute value
  3599. of the specified count.
  3600. ``withscores`` The optional WITHSCORES modifier changes the reply so it
  3601. includes the respective scores of the randomly selected elements from
  3602. the sorted set.
  3603. For more information see https://redis.io/commands/zrandmember
  3604. """
  3605. params = []
  3606. if count is not None:
  3607. params.append(count)
  3608. if withscores:
  3609. params.append("WITHSCORES")
  3610. return self.execute_command("ZRANDMEMBER", key, *params)
  3611. def bzpopmax(self, keys: KeysT, timeout: TimeoutSecT = 0) -> ResponseT:
  3612. """
  3613. ZPOPMAX a value off of the first non-empty sorted set
  3614. named in the ``keys`` list.
  3615. If none of the sorted sets in ``keys`` has a value to ZPOPMAX,
  3616. then block for ``timeout`` seconds, or until a member gets added
  3617. to one of the sorted sets.
  3618. If timeout is 0, then block indefinitely.
  3619. For more information see https://redis.io/commands/bzpopmax
  3620. """
  3621. if timeout is None:
  3622. timeout = 0
  3623. keys = list_or_args(keys, None)
  3624. keys.append(timeout)
  3625. return self.execute_command("BZPOPMAX", *keys)
  3626. def bzpopmin(self, keys: KeysT, timeout: TimeoutSecT = 0) -> ResponseT:
  3627. """
  3628. ZPOPMIN a value off of the first non-empty sorted set
  3629. named in the ``keys`` list.
  3630. If none of the sorted sets in ``keys`` has a value to ZPOPMIN,
  3631. then block for ``timeout`` seconds, or until a member gets added
  3632. to one of the sorted sets.
  3633. If timeout is 0, then block indefinitely.
  3634. For more information see https://redis.io/commands/bzpopmin
  3635. """
  3636. if timeout is None:
  3637. timeout = 0
  3638. keys: list[EncodableT] = list_or_args(keys, None)
  3639. keys.append(timeout)
  3640. return self.execute_command("BZPOPMIN", *keys)
  3641. def zmpop(
  3642. self,
  3643. num_keys: int,
  3644. keys: List[str],
  3645. min: Optional[bool] = False,
  3646. max: Optional[bool] = False,
  3647. count: Optional[int] = 1,
  3648. ) -> Union[Awaitable[list], list]:
  3649. """
  3650. Pop ``count`` values (default 1) off of the first non-empty sorted set
  3651. named in the ``keys`` list.
  3652. For more information see https://redis.io/commands/zmpop
  3653. """
  3654. args = [num_keys] + keys
  3655. if (min and max) or (not min and not max):
  3656. raise DataError
  3657. elif min:
  3658. args.append("MIN")
  3659. else:
  3660. args.append("MAX")
  3661. if count != 1:
  3662. args.extend(["COUNT", count])
  3663. return self.execute_command("ZMPOP", *args)
  3664. def bzmpop(
  3665. self,
  3666. timeout: float,
  3667. numkeys: int,
  3668. keys: List[str],
  3669. min: Optional[bool] = False,
  3670. max: Optional[bool] = False,
  3671. count: Optional[int] = 1,
  3672. ) -> Optional[list]:
  3673. """
  3674. Pop ``count`` values (default 1) off of the first non-empty sorted set
  3675. named in the ``keys`` list.
  3676. If none of the sorted sets in ``keys`` has a value to pop,
  3677. then block for ``timeout`` seconds, or until a member gets added
  3678. to one of the sorted sets.
  3679. If timeout is 0, then block indefinitely.
  3680. For more information see https://redis.io/commands/bzmpop
  3681. """
  3682. args = [timeout, numkeys, *keys]
  3683. if (min and max) or (not min and not max):
  3684. raise DataError("Either min or max, but not both must be set")
  3685. elif min:
  3686. args.append("MIN")
  3687. else:
  3688. args.append("MAX")
  3689. args.extend(["COUNT", count])
  3690. return self.execute_command("BZMPOP", *args)
  3691. def _zrange(
  3692. self,
  3693. command,
  3694. dest: Union[KeyT, None],
  3695. name: KeyT,
  3696. start: int,
  3697. end: int,
  3698. desc: bool = False,
  3699. byscore: bool = False,
  3700. bylex: bool = False,
  3701. withscores: bool = False,
  3702. score_cast_func: Union[type, Callable, None] = float,
  3703. offset: Union[int, None] = None,
  3704. num: Union[int, None] = None,
  3705. ) -> ResponseT:
  3706. if byscore and bylex:
  3707. raise DataError("``byscore`` and ``bylex`` can not be specified together.")
  3708. if (offset is not None and num is None) or (num is not None and offset is None):
  3709. raise DataError("``offset`` and ``num`` must both be specified.")
  3710. if bylex and withscores:
  3711. raise DataError(
  3712. "``withscores`` not supported in combination with ``bylex``."
  3713. )
  3714. pieces = [command]
  3715. if dest:
  3716. pieces.append(dest)
  3717. pieces.extend([name, start, end])
  3718. if byscore:
  3719. pieces.append("BYSCORE")
  3720. if bylex:
  3721. pieces.append("BYLEX")
  3722. if desc:
  3723. pieces.append("REV")
  3724. if offset is not None and num is not None:
  3725. pieces.extend(["LIMIT", offset, num])
  3726. if withscores:
  3727. pieces.append("WITHSCORES")
  3728. options = {"withscores": withscores, "score_cast_func": score_cast_func}
  3729. return self.execute_command(*pieces, **options)
  3730. def zrange(
  3731. self,
  3732. name: KeyT,
  3733. start: int,
  3734. end: int,
  3735. desc: bool = False,
  3736. withscores: bool = False,
  3737. score_cast_func: Union[type, Callable] = float,
  3738. byscore: bool = False,
  3739. bylex: bool = False,
  3740. offset: int = None,
  3741. num: int = None,
  3742. ) -> ResponseT:
  3743. """
  3744. Return a range of values from sorted set ``name`` between
  3745. ``start`` and ``end`` sorted in ascending order.
  3746. ``start`` and ``end`` can be negative, indicating the end of the range.
  3747. ``desc`` a boolean indicating whether to sort the results in reversed
  3748. order.
  3749. ``withscores`` indicates to return the scores along with the values.
  3750. The return type is a list of (value, score) pairs.
  3751. ``score_cast_func`` a callable used to cast the score return value.
  3752. ``byscore`` when set to True, returns the range of elements from the
  3753. sorted set having scores equal or between ``start`` and ``end``.
  3754. ``bylex`` when set to True, returns the range of elements from the
  3755. sorted set between the ``start`` and ``end`` lexicographical closed
  3756. range intervals.
  3757. Valid ``start`` and ``end`` must start with ( or [, in order to specify
  3758. whether the range interval is exclusive or inclusive, respectively.
  3759. ``offset`` and ``num`` are specified, then return a slice of the range.
  3760. Can't be provided when using ``bylex``.
  3761. For more information see https://redis.io/commands/zrange
  3762. """
  3763. # Need to support ``desc`` also when using old redis version
  3764. # because it was supported in 3.5.3 (of redis-py)
  3765. if not byscore and not bylex and (offset is None and num is None) and desc:
  3766. return self.zrevrange(name, start, end, withscores, score_cast_func)
  3767. return self._zrange(
  3768. "ZRANGE",
  3769. None,
  3770. name,
  3771. start,
  3772. end,
  3773. desc,
  3774. byscore,
  3775. bylex,
  3776. withscores,
  3777. score_cast_func,
  3778. offset,
  3779. num,
  3780. )
  3781. def zrevrange(
  3782. self,
  3783. name: KeyT,
  3784. start: int,
  3785. end: int,
  3786. withscores: bool = False,
  3787. score_cast_func: Union[type, Callable] = float,
  3788. ) -> ResponseT:
  3789. """
  3790. Return a range of values from sorted set ``name`` between
  3791. ``start`` and ``end`` sorted in descending order.
  3792. ``start`` and ``end`` can be negative, indicating the end of the range.
  3793. ``withscores`` indicates to return the scores along with the values
  3794. The return type is a list of (value, score) pairs
  3795. ``score_cast_func`` a callable used to cast the score return value
  3796. For more information see https://redis.io/commands/zrevrange
  3797. """
  3798. pieces = ["ZREVRANGE", name, start, end]
  3799. if withscores:
  3800. pieces.append(b"WITHSCORES")
  3801. options = {"withscores": withscores, "score_cast_func": score_cast_func}
  3802. return self.execute_command(*pieces, **options)
  3803. def zrangestore(
  3804. self,
  3805. dest: KeyT,
  3806. name: KeyT,
  3807. start: int,
  3808. end: int,
  3809. byscore: bool = False,
  3810. bylex: bool = False,
  3811. desc: bool = False,
  3812. offset: Union[int, None] = None,
  3813. num: Union[int, None] = None,
  3814. ) -> ResponseT:
  3815. """
  3816. Stores in ``dest`` the result of a range of values from sorted set
  3817. ``name`` between ``start`` and ``end`` sorted in ascending order.
  3818. ``start`` and ``end`` can be negative, indicating the end of the range.
  3819. ``byscore`` when set to True, returns the range of elements from the
  3820. sorted set having scores equal or between ``start`` and ``end``.
  3821. ``bylex`` when set to True, returns the range of elements from the
  3822. sorted set between the ``start`` and ``end`` lexicographical closed
  3823. range intervals.
  3824. Valid ``start`` and ``end`` must start with ( or [, in order to specify
  3825. whether the range interval is exclusive or inclusive, respectively.
  3826. ``desc`` a boolean indicating whether to sort the results in reversed
  3827. order.
  3828. ``offset`` and ``num`` are specified, then return a slice of the range.
  3829. Can't be provided when using ``bylex``.
  3830. For more information see https://redis.io/commands/zrangestore
  3831. """
  3832. return self._zrange(
  3833. "ZRANGESTORE",
  3834. dest,
  3835. name,
  3836. start,
  3837. end,
  3838. desc,
  3839. byscore,
  3840. bylex,
  3841. False,
  3842. None,
  3843. offset,
  3844. num,
  3845. )
  3846. def zrangebylex(
  3847. self,
  3848. name: KeyT,
  3849. min: EncodableT,
  3850. max: EncodableT,
  3851. start: Union[int, None] = None,
  3852. num: Union[int, None] = None,
  3853. ) -> ResponseT:
  3854. """
  3855. Return the lexicographical range of values from sorted set ``name``
  3856. between ``min`` and ``max``.
  3857. If ``start`` and ``num`` are specified, then return a slice of the
  3858. range.
  3859. For more information see https://redis.io/commands/zrangebylex
  3860. """
  3861. if (start is not None and num is None) or (num is not None and start is None):
  3862. raise DataError("``start`` and ``num`` must both be specified")
  3863. pieces = ["ZRANGEBYLEX", name, min, max]
  3864. if start is not None and num is not None:
  3865. pieces.extend([b"LIMIT", start, num])
  3866. return self.execute_command(*pieces)
  3867. def zrevrangebylex(
  3868. self,
  3869. name: KeyT,
  3870. max: EncodableT,
  3871. min: EncodableT,
  3872. start: Union[int, None] = None,
  3873. num: Union[int, None] = None,
  3874. ) -> ResponseT:
  3875. """
  3876. Return the reversed lexicographical range of values from sorted set
  3877. ``name`` between ``max`` and ``min``.
  3878. If ``start`` and ``num`` are specified, then return a slice of the
  3879. range.
  3880. For more information see https://redis.io/commands/zrevrangebylex
  3881. """
  3882. if (start is not None and num is None) or (num is not None and start is None):
  3883. raise DataError("``start`` and ``num`` must both be specified")
  3884. pieces = ["ZREVRANGEBYLEX", name, max, min]
  3885. if start is not None and num is not None:
  3886. pieces.extend(["LIMIT", start, num])
  3887. return self.execute_command(*pieces)
  3888. def zrangebyscore(
  3889. self,
  3890. name: KeyT,
  3891. min: ZScoreBoundT,
  3892. max: ZScoreBoundT,
  3893. start: Union[int, None] = None,
  3894. num: Union[int, None] = None,
  3895. withscores: bool = False,
  3896. score_cast_func: Union[type, Callable] = float,
  3897. ) -> ResponseT:
  3898. """
  3899. Return a range of values from the sorted set ``name`` with scores
  3900. between ``min`` and ``max``.
  3901. If ``start`` and ``num`` are specified, then return a slice
  3902. of the range.
  3903. ``withscores`` indicates to return the scores along with the values.
  3904. The return type is a list of (value, score) pairs
  3905. `score_cast_func`` a callable used to cast the score return value
  3906. For more information see https://redis.io/commands/zrangebyscore
  3907. """
  3908. if (start is not None and num is None) or (num is not None and start is None):
  3909. raise DataError("``start`` and ``num`` must both be specified")
  3910. pieces = ["ZRANGEBYSCORE", name, min, max]
  3911. if start is not None and num is not None:
  3912. pieces.extend(["LIMIT", start, num])
  3913. if withscores:
  3914. pieces.append("WITHSCORES")
  3915. options = {"withscores": withscores, "score_cast_func": score_cast_func}
  3916. return self.execute_command(*pieces, **options)
  3917. def zrevrangebyscore(
  3918. self,
  3919. name: KeyT,
  3920. max: ZScoreBoundT,
  3921. min: ZScoreBoundT,
  3922. start: Union[int, None] = None,
  3923. num: Union[int, None] = None,
  3924. withscores: bool = False,
  3925. score_cast_func: Union[type, Callable] = float,
  3926. ):
  3927. """
  3928. Return a range of values from the sorted set ``name`` with scores
  3929. between ``min`` and ``max`` in descending order.
  3930. If ``start`` and ``num`` are specified, then return a slice
  3931. of the range.
  3932. ``withscores`` indicates to return the scores along with the values.
  3933. The return type is a list of (value, score) pairs
  3934. ``score_cast_func`` a callable used to cast the score return value
  3935. For more information see https://redis.io/commands/zrevrangebyscore
  3936. """
  3937. if (start is not None and num is None) or (num is not None and start is None):
  3938. raise DataError("``start`` and ``num`` must both be specified")
  3939. pieces = ["ZREVRANGEBYSCORE", name, max, min]
  3940. if start is not None and num is not None:
  3941. pieces.extend(["LIMIT", start, num])
  3942. if withscores:
  3943. pieces.append("WITHSCORES")
  3944. options = {"withscores": withscores, "score_cast_func": score_cast_func}
  3945. return self.execute_command(*pieces, **options)
  3946. def zrank(
  3947. self,
  3948. name: KeyT,
  3949. value: EncodableT,
  3950. withscore: bool = False,
  3951. ) -> ResponseT:
  3952. """
  3953. Returns a 0-based value indicating the rank of ``value`` in sorted set
  3954. ``name``.
  3955. The optional WITHSCORE argument supplements the command's
  3956. reply with the score of the element returned.
  3957. For more information see https://redis.io/commands/zrank
  3958. """
  3959. if withscore:
  3960. return self.execute_command("ZRANK", name, value, "WITHSCORE")
  3961. return self.execute_command("ZRANK", name, value)
  3962. def zrem(self, name: KeyT, *values: FieldT) -> ResponseT:
  3963. """
  3964. Remove member ``values`` from sorted set ``name``
  3965. For more information see https://redis.io/commands/zrem
  3966. """
  3967. return self.execute_command("ZREM", name, *values)
  3968. def zremrangebylex(self, name: KeyT, min: EncodableT, max: EncodableT) -> ResponseT:
  3969. """
  3970. Remove all elements in the sorted set ``name`` between the
  3971. lexicographical range specified by ``min`` and ``max``.
  3972. Returns the number of elements removed.
  3973. For more information see https://redis.io/commands/zremrangebylex
  3974. """
  3975. return self.execute_command("ZREMRANGEBYLEX", name, min, max)
  3976. def zremrangebyrank(self, name: KeyT, min: int, max: int) -> ResponseT:
  3977. """
  3978. Remove all elements in the sorted set ``name`` with ranks between
  3979. ``min`` and ``max``. Values are 0-based, ordered from smallest score
  3980. to largest. Values can be negative indicating the highest scores.
  3981. Returns the number of elements removed
  3982. For more information see https://redis.io/commands/zremrangebyrank
  3983. """
  3984. return self.execute_command("ZREMRANGEBYRANK", name, min, max)
  3985. def zremrangebyscore(
  3986. self, name: KeyT, min: ZScoreBoundT, max: ZScoreBoundT
  3987. ) -> ResponseT:
  3988. """
  3989. Remove all elements in the sorted set ``name`` with scores
  3990. between ``min`` and ``max``. Returns the number of elements removed.
  3991. For more information see https://redis.io/commands/zremrangebyscore
  3992. """
  3993. return self.execute_command("ZREMRANGEBYSCORE", name, min, max)
  3994. def zrevrank(
  3995. self,
  3996. name: KeyT,
  3997. value: EncodableT,
  3998. withscore: bool = False,
  3999. ) -> ResponseT:
  4000. """
  4001. Returns a 0-based value indicating the descending rank of
  4002. ``value`` in sorted set ``name``.
  4003. The optional ``withscore`` argument supplements the command's
  4004. reply with the score of the element returned.
  4005. For more information see https://redis.io/commands/zrevrank
  4006. """
  4007. if withscore:
  4008. return self.execute_command("ZREVRANK", name, value, "WITHSCORE")
  4009. return self.execute_command("ZREVRANK", name, value)
  4010. def zscore(self, name: KeyT, value: EncodableT) -> ResponseT:
  4011. """
  4012. Return the score of element ``value`` in sorted set ``name``
  4013. For more information see https://redis.io/commands/zscore
  4014. """
  4015. return self.execute_command("ZSCORE", name, value)
  4016. def zunion(
  4017. self,
  4018. keys: Union[Sequence[KeyT], Mapping[AnyKeyT, float]],
  4019. aggregate: Union[str, None] = None,
  4020. withscores: bool = False,
  4021. ) -> ResponseT:
  4022. """
  4023. Return the union of multiple sorted sets specified by ``keys``.
  4024. ``keys`` can be provided as dictionary of keys and their weights.
  4025. Scores will be aggregated based on the ``aggregate``, or SUM if
  4026. none is provided.
  4027. For more information see https://redis.io/commands/zunion
  4028. """
  4029. return self._zaggregate("ZUNION", None, keys, aggregate, withscores=withscores)
  4030. def zunionstore(
  4031. self,
  4032. dest: KeyT,
  4033. keys: Union[Sequence[KeyT], Mapping[AnyKeyT, float]],
  4034. aggregate: Union[str, None] = None,
  4035. ) -> ResponseT:
  4036. """
  4037. Union multiple sorted sets specified by ``keys`` into
  4038. a new sorted set, ``dest``. Scores in the destination will be
  4039. aggregated based on the ``aggregate``, or SUM if none is provided.
  4040. For more information see https://redis.io/commands/zunionstore
  4041. """
  4042. return self._zaggregate("ZUNIONSTORE", dest, keys, aggregate)
  4043. def zmscore(self, key: KeyT, members: List[str]) -> ResponseT:
  4044. """
  4045. Returns the scores associated with the specified members
  4046. in the sorted set stored at key.
  4047. ``members`` should be a list of the member name.
  4048. Return type is a list of score.
  4049. If the member does not exist, a None will be returned
  4050. in corresponding position.
  4051. For more information see https://redis.io/commands/zmscore
  4052. """
  4053. if not members:
  4054. raise DataError("ZMSCORE members must be a non-empty list")
  4055. pieces = [key] + members
  4056. return self.execute_command("ZMSCORE", *pieces)
  4057. def _zaggregate(
  4058. self,
  4059. command: str,
  4060. dest: Union[KeyT, None],
  4061. keys: Union[Sequence[KeyT], Mapping[AnyKeyT, float]],
  4062. aggregate: Union[str, None] = None,
  4063. **options,
  4064. ) -> ResponseT:
  4065. pieces: list[EncodableT] = [command]
  4066. if dest is not None:
  4067. pieces.append(dest)
  4068. pieces.append(len(keys))
  4069. if isinstance(keys, dict):
  4070. keys, weights = keys.keys(), keys.values()
  4071. else:
  4072. weights = None
  4073. pieces.extend(keys)
  4074. if weights:
  4075. pieces.append(b"WEIGHTS")
  4076. pieces.extend(weights)
  4077. if aggregate:
  4078. if aggregate.upper() in ["SUM", "MIN", "MAX"]:
  4079. pieces.append(b"AGGREGATE")
  4080. pieces.append(aggregate)
  4081. else:
  4082. raise DataError("aggregate can be sum, min or max.")
  4083. if options.get("withscores", False):
  4084. pieces.append(b"WITHSCORES")
  4085. return self.execute_command(*pieces, **options)
  4086. AsyncSortedSetCommands = SortedSetCommands
  4087. class HyperlogCommands(CommandsProtocol):
  4088. """
  4089. Redis commands of HyperLogLogs data type.
  4090. see: https://redis.io/topics/data-types-intro#hyperloglogs
  4091. """
  4092. def pfadd(self, name: KeyT, *values: FieldT) -> ResponseT:
  4093. """
  4094. Adds the specified elements to the specified HyperLogLog.
  4095. For more information see https://redis.io/commands/pfadd
  4096. """
  4097. return self.execute_command("PFADD", name, *values)
  4098. def pfcount(self, *sources: KeyT) -> ResponseT:
  4099. """
  4100. Return the approximated cardinality of
  4101. the set observed by the HyperLogLog at key(s).
  4102. For more information see https://redis.io/commands/pfcount
  4103. """
  4104. return self.execute_command("PFCOUNT", *sources)
  4105. def pfmerge(self, dest: KeyT, *sources: KeyT) -> ResponseT:
  4106. """
  4107. Merge N different HyperLogLogs into a single one.
  4108. For more information see https://redis.io/commands/pfmerge
  4109. """
  4110. return self.execute_command("PFMERGE", dest, *sources)
  4111. AsyncHyperlogCommands = HyperlogCommands
  4112. class HashCommands(CommandsProtocol):
  4113. """
  4114. Redis commands for Hash data type.
  4115. see: https://redis.io/topics/data-types-intro#redis-hashes
  4116. """
  4117. def hdel(self, name: str, *keys: str) -> Union[Awaitable[int], int]:
  4118. """
  4119. Delete ``keys`` from hash ``name``
  4120. For more information see https://redis.io/commands/hdel
  4121. """
  4122. return self.execute_command("HDEL", name, *keys)
  4123. def hexists(self, name: str, key: str) -> Union[Awaitable[bool], bool]:
  4124. """
  4125. Returns a boolean indicating if ``key`` exists within hash ``name``
  4126. For more information see https://redis.io/commands/hexists
  4127. """
  4128. return self.execute_command("HEXISTS", name, key)
  4129. def hget(
  4130. self, name: str, key: str
  4131. ) -> Union[Awaitable[Optional[str]], Optional[str]]:
  4132. """
  4133. Return the value of ``key`` within the hash ``name``
  4134. For more information see https://redis.io/commands/hget
  4135. """
  4136. return self.execute_command("HGET", name, key)
  4137. def hgetall(self, name: str) -> Union[Awaitable[dict], dict]:
  4138. """
  4139. Return a Python dict of the hash's name/value pairs
  4140. For more information see https://redis.io/commands/hgetall
  4141. """
  4142. return self.execute_command("HGETALL", name)
  4143. def hincrby(
  4144. self, name: str, key: str, amount: int = 1
  4145. ) -> Union[Awaitable[int], int]:
  4146. """
  4147. Increment the value of ``key`` in hash ``name`` by ``amount``
  4148. For more information see https://redis.io/commands/hincrby
  4149. """
  4150. return self.execute_command("HINCRBY", name, key, amount)
  4151. def hincrbyfloat(
  4152. self, name: str, key: str, amount: float = 1.0
  4153. ) -> Union[Awaitable[float], float]:
  4154. """
  4155. Increment the value of ``key`` in hash ``name`` by floating ``amount``
  4156. For more information see https://redis.io/commands/hincrbyfloat
  4157. """
  4158. return self.execute_command("HINCRBYFLOAT", name, key, amount)
  4159. def hkeys(self, name: str) -> Union[Awaitable[List], List]:
  4160. """
  4161. Return the list of keys within hash ``name``
  4162. For more information see https://redis.io/commands/hkeys
  4163. """
  4164. return self.execute_command("HKEYS", name)
  4165. def hlen(self, name: str) -> Union[Awaitable[int], int]:
  4166. """
  4167. Return the number of elements in hash ``name``
  4168. For more information see https://redis.io/commands/hlen
  4169. """
  4170. return self.execute_command("HLEN", name)
  4171. def hset(
  4172. self,
  4173. name: str,
  4174. key: Optional[str] = None,
  4175. value: Optional[str] = None,
  4176. mapping: Optional[dict] = None,
  4177. items: Optional[list] = None,
  4178. ) -> Union[Awaitable[int], int]:
  4179. """
  4180. Set ``key`` to ``value`` within hash ``name``,
  4181. ``mapping`` accepts a dict of key/value pairs that will be
  4182. added to hash ``name``.
  4183. ``items`` accepts a list of key/value pairs that will be
  4184. added to hash ``name``.
  4185. Returns the number of fields that were added.
  4186. For more information see https://redis.io/commands/hset
  4187. """
  4188. if key is None and not mapping and not items:
  4189. raise DataError("'hset' with no key value pairs")
  4190. pieces = []
  4191. if items:
  4192. pieces.extend(items)
  4193. if key is not None:
  4194. pieces.extend((key, value))
  4195. if mapping:
  4196. for pair in mapping.items():
  4197. pieces.extend(pair)
  4198. return self.execute_command("HSET", name, *pieces)
  4199. def hsetnx(self, name: str, key: str, value: str) -> Union[Awaitable[bool], bool]:
  4200. """
  4201. Set ``key`` to ``value`` within hash ``name`` if ``key`` does not
  4202. exist. Returns 1 if HSETNX created a field, otherwise 0.
  4203. For more information see https://redis.io/commands/hsetnx
  4204. """
  4205. return self.execute_command("HSETNX", name, key, value)
  4206. def hmset(self, name: str, mapping: dict) -> Union[Awaitable[str], str]:
  4207. """
  4208. Set key to value within hash ``name`` for each corresponding
  4209. key and value from the ``mapping`` dict.
  4210. For more information see https://redis.io/commands/hmset
  4211. """
  4212. warnings.warn(
  4213. f"{self.__class__.__name__}.hmset() is deprecated. "
  4214. f"Use {self.__class__.__name__}.hset() instead.",
  4215. DeprecationWarning,
  4216. stacklevel=2,
  4217. )
  4218. if not mapping:
  4219. raise DataError("'hmset' with 'mapping' of length 0")
  4220. items = []
  4221. for pair in mapping.items():
  4222. items.extend(pair)
  4223. return self.execute_command("HMSET", name, *items)
  4224. def hmget(self, name: str, keys: List, *args: List) -> Union[Awaitable[List], List]:
  4225. """
  4226. Returns a list of values ordered identically to ``keys``
  4227. For more information see https://redis.io/commands/hmget
  4228. """
  4229. args = list_or_args(keys, args)
  4230. return self.execute_command("HMGET", name, *args)
  4231. def hvals(self, name: str) -> Union[Awaitable[List], List]:
  4232. """
  4233. Return the list of values within hash ``name``
  4234. For more information see https://redis.io/commands/hvals
  4235. """
  4236. return self.execute_command("HVALS", name)
  4237. def hstrlen(self, name: str, key: str) -> Union[Awaitable[int], int]:
  4238. """
  4239. Return the number of bytes stored in the value of ``key``
  4240. within hash ``name``
  4241. For more information see https://redis.io/commands/hstrlen
  4242. """
  4243. return self.execute_command("HSTRLEN", name, key)
  4244. def hexpire(
  4245. self,
  4246. name: KeyT,
  4247. seconds: ExpiryT,
  4248. *fields: str,
  4249. nx: bool = False,
  4250. xx: bool = False,
  4251. gt: bool = False,
  4252. lt: bool = False,
  4253. ) -> ResponseT:
  4254. """
  4255. Sets or updates the expiration time for fields within a hash key, using relative
  4256. time in seconds.
  4257. If a field already has an expiration time, the behavior of the update can be
  4258. controlled using the `nx`, `xx`, `gt`, and `lt` parameters.
  4259. The return value provides detailed information about the outcome for each field.
  4260. For more information, see https://redis.io/commands/hexpire
  4261. Args:
  4262. name: The name of the hash key.
  4263. seconds: Expiration time in seconds, relative. Can be an integer, or a
  4264. Python `timedelta` object.
  4265. fields: List of fields within the hash to apply the expiration time to.
  4266. nx: Set expiry only when the field has no expiry.
  4267. xx: Set expiry only when the field has an existing expiry.
  4268. gt: Set expiry only when the new expiry is greater than the current one.
  4269. lt: Set expiry only when the new expiry is less than the current one.
  4270. Returns:
  4271. Returns a list which contains for each field in the request:
  4272. - `-2` if the field does not exist, or if the key does not exist.
  4273. - `0` if the specified NX | XX | GT | LT condition was not met.
  4274. - `1` if the expiration time was set or updated.
  4275. - `2` if the field was deleted because the specified expiration time is
  4276. in the past.
  4277. """
  4278. conditions = [nx, xx, gt, lt]
  4279. if sum(conditions) > 1:
  4280. raise ValueError("Only one of 'nx', 'xx', 'gt', 'lt' can be specified.")
  4281. if isinstance(seconds, datetime.timedelta):
  4282. seconds = int(seconds.total_seconds())
  4283. options = []
  4284. if nx:
  4285. options.append("NX")
  4286. if xx:
  4287. options.append("XX")
  4288. if gt:
  4289. options.append("GT")
  4290. if lt:
  4291. options.append("LT")
  4292. return self.execute_command(
  4293. "HEXPIRE", name, seconds, *options, "FIELDS", len(fields), *fields
  4294. )
  4295. def hpexpire(
  4296. self,
  4297. name: KeyT,
  4298. milliseconds: ExpiryT,
  4299. *fields: str,
  4300. nx: bool = False,
  4301. xx: bool = False,
  4302. gt: bool = False,
  4303. lt: bool = False,
  4304. ) -> ResponseT:
  4305. """
  4306. Sets or updates the expiration time for fields within a hash key, using relative
  4307. time in milliseconds.
  4308. If a field already has an expiration time, the behavior of the update can be
  4309. controlled using the `nx`, `xx`, `gt`, and `lt` parameters.
  4310. The return value provides detailed information about the outcome for each field.
  4311. For more information, see https://redis.io/commands/hpexpire
  4312. Args:
  4313. name: The name of the hash key.
  4314. milliseconds: Expiration time in milliseconds, relative. Can be an integer,
  4315. or a Python `timedelta` object.
  4316. fields: List of fields within the hash to apply the expiration time to.
  4317. nx: Set expiry only when the field has no expiry.
  4318. xx: Set expiry only when the field has an existing expiry.
  4319. gt: Set expiry only when the new expiry is greater than the current one.
  4320. lt: Set expiry only when the new expiry is less than the current one.
  4321. Returns:
  4322. Returns a list which contains for each field in the request:
  4323. - `-2` if the field does not exist, or if the key does not exist.
  4324. - `0` if the specified NX | XX | GT | LT condition was not met.
  4325. - `1` if the expiration time was set or updated.
  4326. - `2` if the field was deleted because the specified expiration time is
  4327. in the past.
  4328. """
  4329. conditions = [nx, xx, gt, lt]
  4330. if sum(conditions) > 1:
  4331. raise ValueError("Only one of 'nx', 'xx', 'gt', 'lt' can be specified.")
  4332. if isinstance(milliseconds, datetime.timedelta):
  4333. milliseconds = int(milliseconds.total_seconds() * 1000)
  4334. options = []
  4335. if nx:
  4336. options.append("NX")
  4337. if xx:
  4338. options.append("XX")
  4339. if gt:
  4340. options.append("GT")
  4341. if lt:
  4342. options.append("LT")
  4343. return self.execute_command(
  4344. "HPEXPIRE", name, milliseconds, *options, "FIELDS", len(fields), *fields
  4345. )
  4346. def hexpireat(
  4347. self,
  4348. name: KeyT,
  4349. unix_time_seconds: AbsExpiryT,
  4350. *fields: str,
  4351. nx: bool = False,
  4352. xx: bool = False,
  4353. gt: bool = False,
  4354. lt: bool = False,
  4355. ) -> ResponseT:
  4356. """
  4357. Sets or updates the expiration time for fields within a hash key, using an
  4358. absolute Unix timestamp in seconds.
  4359. If a field already has an expiration time, the behavior of the update can be
  4360. controlled using the `nx`, `xx`, `gt`, and `lt` parameters.
  4361. The return value provides detailed information about the outcome for each field.
  4362. For more information, see https://redis.io/commands/hexpireat
  4363. Args:
  4364. name: The name of the hash key.
  4365. unix_time_seconds: Expiration time as Unix timestamp in seconds. Can be an
  4366. integer or a Python `datetime` object.
  4367. fields: List of fields within the hash to apply the expiration time to.
  4368. nx: Set expiry only when the field has no expiry.
  4369. xx: Set expiry only when the field has an existing expiration time.
  4370. gt: Set expiry only when the new expiry is greater than the current one.
  4371. lt: Set expiry only when the new expiry is less than the current one.
  4372. Returns:
  4373. Returns a list which contains for each field in the request:
  4374. - `-2` if the field does not exist, or if the key does not exist.
  4375. - `0` if the specified NX | XX | GT | LT condition was not met.
  4376. - `1` if the expiration time was set or updated.
  4377. - `2` if the field was deleted because the specified expiration time is
  4378. in the past.
  4379. """
  4380. conditions = [nx, xx, gt, lt]
  4381. if sum(conditions) > 1:
  4382. raise ValueError("Only one of 'nx', 'xx', 'gt', 'lt' can be specified.")
  4383. if isinstance(unix_time_seconds, datetime.datetime):
  4384. unix_time_seconds = int(unix_time_seconds.timestamp())
  4385. options = []
  4386. if nx:
  4387. options.append("NX")
  4388. if xx:
  4389. options.append("XX")
  4390. if gt:
  4391. options.append("GT")
  4392. if lt:
  4393. options.append("LT")
  4394. return self.execute_command(
  4395. "HEXPIREAT",
  4396. name,
  4397. unix_time_seconds,
  4398. *options,
  4399. "FIELDS",
  4400. len(fields),
  4401. *fields,
  4402. )
  4403. def hpexpireat(
  4404. self,
  4405. name: KeyT,
  4406. unix_time_milliseconds: AbsExpiryT,
  4407. *fields: str,
  4408. nx: bool = False,
  4409. xx: bool = False,
  4410. gt: bool = False,
  4411. lt: bool = False,
  4412. ) -> ResponseT:
  4413. """
  4414. Sets or updates the expiration time for fields within a hash key, using an
  4415. absolute Unix timestamp in milliseconds.
  4416. If a field already has an expiration time, the behavior of the update can be
  4417. controlled using the `nx`, `xx`, `gt`, and `lt` parameters.
  4418. The return value provides detailed information about the outcome for each field.
  4419. For more information, see https://redis.io/commands/hpexpireat
  4420. Args:
  4421. name: The name of the hash key.
  4422. unix_time_milliseconds: Expiration time as Unix timestamp in milliseconds.
  4423. Can be an integer or a Python `datetime` object.
  4424. fields: List of fields within the hash to apply the expiry.
  4425. nx: Set expiry only when the field has no expiry.
  4426. xx: Set expiry only when the field has an existing expiry.
  4427. gt: Set expiry only when the new expiry is greater than the current one.
  4428. lt: Set expiry only when the new expiry is less than the current one.
  4429. Returns:
  4430. Returns a list which contains for each field in the request:
  4431. - `-2` if the field does not exist, or if the key does not exist.
  4432. - `0` if the specified NX | XX | GT | LT condition was not met.
  4433. - `1` if the expiration time was set or updated.
  4434. - `2` if the field was deleted because the specified expiration time is
  4435. in the past.
  4436. """
  4437. conditions = [nx, xx, gt, lt]
  4438. if sum(conditions) > 1:
  4439. raise ValueError("Only one of 'nx', 'xx', 'gt', 'lt' can be specified.")
  4440. if isinstance(unix_time_milliseconds, datetime.datetime):
  4441. unix_time_milliseconds = int(unix_time_milliseconds.timestamp() * 1000)
  4442. options = []
  4443. if nx:
  4444. options.append("NX")
  4445. if xx:
  4446. options.append("XX")
  4447. if gt:
  4448. options.append("GT")
  4449. if lt:
  4450. options.append("LT")
  4451. return self.execute_command(
  4452. "HPEXPIREAT",
  4453. name,
  4454. unix_time_milliseconds,
  4455. *options,
  4456. "FIELDS",
  4457. len(fields),
  4458. *fields,
  4459. )
  4460. def hpersist(self, name: KeyT, *fields: str) -> ResponseT:
  4461. """
  4462. Removes the expiration time for each specified field in a hash.
  4463. For more information, see https://redis.io/commands/hpersist
  4464. Args:
  4465. name: The name of the hash key.
  4466. fields: A list of fields within the hash from which to remove the
  4467. expiration time.
  4468. Returns:
  4469. Returns a list which contains for each field in the request:
  4470. - `-2` if the field does not exist, or if the key does not exist.
  4471. - `-1` if the field exists but has no associated expiration time.
  4472. - `1` if the expiration time was successfully removed from the field.
  4473. """
  4474. return self.execute_command("HPERSIST", name, "FIELDS", len(fields), *fields)
  4475. def hexpiretime(self, key: KeyT, *fields: str) -> ResponseT:
  4476. """
  4477. Returns the expiration times of hash fields as Unix timestamps in seconds.
  4478. For more information, see https://redis.io/commands/hexpiretime
  4479. Args:
  4480. key: The hash key.
  4481. fields: A list of fields within the hash for which to get the expiration
  4482. time.
  4483. Returns:
  4484. Returns a list which contains for each field in the request:
  4485. - `-2` if the field does not exist, or if the key does not exist.
  4486. - `-1` if the field exists but has no associated expire time.
  4487. - A positive integer representing the expiration Unix timestamp in
  4488. seconds, if the field has an associated expiration time.
  4489. """
  4490. return self.execute_command("HEXPIRETIME", key, "FIELDS", len(fields), *fields)
  4491. def hpexpiretime(self, key: KeyT, *fields: str) -> ResponseT:
  4492. """
  4493. Returns the expiration times of hash fields as Unix timestamps in milliseconds.
  4494. For more information, see https://redis.io/commands/hpexpiretime
  4495. Args:
  4496. key: The hash key.
  4497. fields: A list of fields within the hash for which to get the expiration
  4498. time.
  4499. Returns:
  4500. Returns a list which contains for each field in the request:
  4501. - `-2` if the field does not exist, or if the key does not exist.
  4502. - `-1` if the field exists but has no associated expire time.
  4503. - A positive integer representing the expiration Unix timestamp in
  4504. milliseconds, if the field has an associated expiration time.
  4505. """
  4506. return self.execute_command("HPEXPIRETIME", key, "FIELDS", len(fields), *fields)
  4507. def httl(self, key: KeyT, *fields: str) -> ResponseT:
  4508. """
  4509. Returns the TTL (Time To Live) in seconds for each specified field within a hash
  4510. key.
  4511. For more information, see https://redis.io/commands/httl
  4512. Args:
  4513. key: The hash key.
  4514. fields: A list of fields within the hash for which to get the TTL.
  4515. Returns:
  4516. Returns a list which contains for each field in the request:
  4517. - `-2` if the field does not exist, or if the key does not exist.
  4518. - `-1` if the field exists but has no associated expire time.
  4519. - A positive integer representing the TTL in seconds if the field has
  4520. an associated expiration time.
  4521. """
  4522. return self.execute_command("HTTL", key, "FIELDS", len(fields), *fields)
  4523. def hpttl(self, key: KeyT, *fields: str) -> ResponseT:
  4524. """
  4525. Returns the TTL (Time To Live) in milliseconds for each specified field within a
  4526. hash key.
  4527. For more information, see https://redis.io/commands/hpttl
  4528. Args:
  4529. key: The hash key.
  4530. fields: A list of fields within the hash for which to get the TTL.
  4531. Returns:
  4532. Returns a list which contains for each field in the request:
  4533. - `-2` if the field does not exist, or if the key does not exist.
  4534. - `-1` if the field exists but has no associated expire time.
  4535. - A positive integer representing the TTL in milliseconds if the field
  4536. has an associated expiration time.
  4537. """
  4538. return self.execute_command("HPTTL", key, "FIELDS", len(fields), *fields)
  4539. AsyncHashCommands = HashCommands
  4540. class Script:
  4541. """
  4542. An executable Lua script object returned by ``register_script``
  4543. """
  4544. def __init__(self, registered_client: "Redis", script: ScriptTextT):
  4545. self.registered_client = registered_client
  4546. self.script = script
  4547. # Precalculate and store the SHA1 hex digest of the script.
  4548. if isinstance(script, str):
  4549. # We need the encoding from the client in order to generate an
  4550. # accurate byte representation of the script
  4551. try:
  4552. encoder = registered_client.connection_pool.get_encoder()
  4553. except AttributeError:
  4554. # Cluster
  4555. encoder = registered_client.get_encoder()
  4556. script = encoder.encode(script)
  4557. self.sha = hashlib.sha1(script).hexdigest()
  4558. def __call__(
  4559. self,
  4560. keys: Union[Sequence[KeyT], None] = None,
  4561. args: Union[Iterable[EncodableT], None] = None,
  4562. client: Union["Redis", None] = None,
  4563. ):
  4564. """Execute the script, passing any required ``args``"""
  4565. keys = keys or []
  4566. args = args or []
  4567. if client is None:
  4568. client = self.registered_client
  4569. args = tuple(keys) + tuple(args)
  4570. # make sure the Redis server knows about the script
  4571. from redis.client import Pipeline
  4572. if isinstance(client, Pipeline):
  4573. # Make sure the pipeline can register the script before executing.
  4574. client.scripts.add(self)
  4575. try:
  4576. return client.evalsha(self.sha, len(keys), *args)
  4577. except NoScriptError:
  4578. # Maybe the client is pointed to a different server than the client
  4579. # that created this instance?
  4580. # Overwrite the sha just in case there was a discrepancy.
  4581. self.sha = client.script_load(self.script)
  4582. return client.evalsha(self.sha, len(keys), *args)
  4583. class AsyncScript:
  4584. """
  4585. An executable Lua script object returned by ``register_script``
  4586. """
  4587. def __init__(self, registered_client: "AsyncRedis", script: ScriptTextT):
  4588. self.registered_client = registered_client
  4589. self.script = script
  4590. # Precalculate and store the SHA1 hex digest of the script.
  4591. if isinstance(script, str):
  4592. # We need the encoding from the client in order to generate an
  4593. # accurate byte representation of the script
  4594. try:
  4595. encoder = registered_client.connection_pool.get_encoder()
  4596. except AttributeError:
  4597. # Cluster
  4598. encoder = registered_client.get_encoder()
  4599. script = encoder.encode(script)
  4600. self.sha = hashlib.sha1(script).hexdigest()
  4601. async def __call__(
  4602. self,
  4603. keys: Union[Sequence[KeyT], None] = None,
  4604. args: Union[Iterable[EncodableT], None] = None,
  4605. client: Union["AsyncRedis", None] = None,
  4606. ):
  4607. """Execute the script, passing any required ``args``"""
  4608. keys = keys or []
  4609. args = args or []
  4610. if client is None:
  4611. client = self.registered_client
  4612. args = tuple(keys) + tuple(args)
  4613. # make sure the Redis server knows about the script
  4614. from redis.asyncio.client import Pipeline
  4615. if isinstance(client, Pipeline):
  4616. # Make sure the pipeline can register the script before executing.
  4617. client.scripts.add(self)
  4618. try:
  4619. return await client.evalsha(self.sha, len(keys), *args)
  4620. except NoScriptError:
  4621. # Maybe the client is pointed to a different server than the client
  4622. # that created this instance?
  4623. # Overwrite the sha just in case there was a discrepancy.
  4624. self.sha = await client.script_load(self.script)
  4625. return await client.evalsha(self.sha, len(keys), *args)
  4626. class PubSubCommands(CommandsProtocol):
  4627. """
  4628. Redis PubSub commands.
  4629. see https://redis.io/topics/pubsub
  4630. """
  4631. def publish(self, channel: ChannelT, message: EncodableT, **kwargs) -> ResponseT:
  4632. """
  4633. Publish ``message`` on ``channel``.
  4634. Returns the number of subscribers the message was delivered to.
  4635. For more information see https://redis.io/commands/publish
  4636. """
  4637. return self.execute_command("PUBLISH", channel, message, **kwargs)
  4638. def spublish(self, shard_channel: ChannelT, message: EncodableT) -> ResponseT:
  4639. """
  4640. Posts a message to the given shard channel.
  4641. Returns the number of clients that received the message
  4642. For more information see https://redis.io/commands/spublish
  4643. """
  4644. return self.execute_command("SPUBLISH", shard_channel, message)
  4645. def pubsub_channels(self, pattern: PatternT = "*", **kwargs) -> ResponseT:
  4646. """
  4647. Return a list of channels that have at least one subscriber
  4648. For more information see https://redis.io/commands/pubsub-channels
  4649. """
  4650. return self.execute_command("PUBSUB CHANNELS", pattern, **kwargs)
  4651. def pubsub_shardchannels(self, pattern: PatternT = "*", **kwargs) -> ResponseT:
  4652. """
  4653. Return a list of shard_channels that have at least one subscriber
  4654. For more information see https://redis.io/commands/pubsub-shardchannels
  4655. """
  4656. return self.execute_command("PUBSUB SHARDCHANNELS", pattern, **kwargs)
  4657. def pubsub_numpat(self, **kwargs) -> ResponseT:
  4658. """
  4659. Returns the number of subscriptions to patterns
  4660. For more information see https://redis.io/commands/pubsub-numpat
  4661. """
  4662. return self.execute_command("PUBSUB NUMPAT", **kwargs)
  4663. def pubsub_numsub(self, *args: ChannelT, **kwargs) -> ResponseT:
  4664. """
  4665. Return a list of (channel, number of subscribers) tuples
  4666. for each channel given in ``*args``
  4667. For more information see https://redis.io/commands/pubsub-numsub
  4668. """
  4669. return self.execute_command("PUBSUB NUMSUB", *args, **kwargs)
  4670. def pubsub_shardnumsub(self, *args: ChannelT, **kwargs) -> ResponseT:
  4671. """
  4672. Return a list of (shard_channel, number of subscribers) tuples
  4673. for each channel given in ``*args``
  4674. For more information see https://redis.io/commands/pubsub-shardnumsub
  4675. """
  4676. return self.execute_command("PUBSUB SHARDNUMSUB", *args, **kwargs)
  4677. AsyncPubSubCommands = PubSubCommands
  4678. class ScriptCommands(CommandsProtocol):
  4679. """
  4680. Redis Lua script commands. see:
  4681. https://redis.io/ebook/part-3-next-steps/chapter-11-scripting-redis-with-lua/
  4682. """
  4683. def _eval(
  4684. self, command: str, script: str, numkeys: int, *keys_and_args: str
  4685. ) -> Union[Awaitable[str], str]:
  4686. return self.execute_command(command, script, numkeys, *keys_and_args)
  4687. def eval(
  4688. self, script: str, numkeys: int, *keys_and_args: str
  4689. ) -> Union[Awaitable[str], str]:
  4690. """
  4691. Execute the Lua ``script``, specifying the ``numkeys`` the script
  4692. will touch and the key names and argument values in ``keys_and_args``.
  4693. Returns the result of the script.
  4694. In practice, use the object returned by ``register_script``. This
  4695. function exists purely for Redis API completion.
  4696. For more information see https://redis.io/commands/eval
  4697. """
  4698. return self._eval("EVAL", script, numkeys, *keys_and_args)
  4699. def eval_ro(
  4700. self, script: str, numkeys: int, *keys_and_args: str
  4701. ) -> Union[Awaitable[str], str]:
  4702. """
  4703. The read-only variant of the EVAL command
  4704. Execute the read-only Lua ``script`` specifying the ``numkeys`` the script
  4705. will touch and the key names and argument values in ``keys_and_args``.
  4706. Returns the result of the script.
  4707. For more information see https://redis.io/commands/eval_ro
  4708. """
  4709. return self._eval("EVAL_RO", script, numkeys, *keys_and_args)
  4710. def _evalsha(
  4711. self, command: str, sha: str, numkeys: int, *keys_and_args: list
  4712. ) -> Union[Awaitable[str], str]:
  4713. return self.execute_command(command, sha, numkeys, *keys_and_args)
  4714. def evalsha(
  4715. self, sha: str, numkeys: int, *keys_and_args: str
  4716. ) -> Union[Awaitable[str], str]:
  4717. """
  4718. Use the ``sha`` to execute a Lua script already registered via EVAL
  4719. or SCRIPT LOAD. Specify the ``numkeys`` the script will touch and the
  4720. key names and argument values in ``keys_and_args``. Returns the result
  4721. of the script.
  4722. In practice, use the object returned by ``register_script``. This
  4723. function exists purely for Redis API completion.
  4724. For more information see https://redis.io/commands/evalsha
  4725. """
  4726. return self._evalsha("EVALSHA", sha, numkeys, *keys_and_args)
  4727. def evalsha_ro(
  4728. self, sha: str, numkeys: int, *keys_and_args: str
  4729. ) -> Union[Awaitable[str], str]:
  4730. """
  4731. The read-only variant of the EVALSHA command
  4732. Use the ``sha`` to execute a read-only Lua script already registered via EVAL
  4733. or SCRIPT LOAD. Specify the ``numkeys`` the script will touch and the
  4734. key names and argument values in ``keys_and_args``. Returns the result
  4735. of the script.
  4736. For more information see https://redis.io/commands/evalsha_ro
  4737. """
  4738. return self._evalsha("EVALSHA_RO", sha, numkeys, *keys_and_args)
  4739. def script_exists(self, *args: str) -> ResponseT:
  4740. """
  4741. Check if a script exists in the script cache by specifying the SHAs of
  4742. each script as ``args``. Returns a list of boolean values indicating if
  4743. if each already script exists in the cache.
  4744. For more information see https://redis.io/commands/script-exists
  4745. """
  4746. return self.execute_command("SCRIPT EXISTS", *args)
  4747. def script_debug(self, *args) -> None:
  4748. raise NotImplementedError(
  4749. "SCRIPT DEBUG is intentionally not implemented in the client."
  4750. )
  4751. def script_flush(
  4752. self, sync_type: Union[Literal["SYNC"], Literal["ASYNC"]] = None
  4753. ) -> ResponseT:
  4754. """Flush all scripts from the script cache.
  4755. ``sync_type`` is by default SYNC (synchronous) but it can also be
  4756. ASYNC.
  4757. For more information see https://redis.io/commands/script-flush
  4758. """
  4759. # Redis pre 6 had no sync_type.
  4760. if sync_type not in ["SYNC", "ASYNC", None]:
  4761. raise DataError(
  4762. "SCRIPT FLUSH defaults to SYNC in redis > 6.2, or "
  4763. "accepts SYNC/ASYNC. For older versions, "
  4764. "of redis leave as None."
  4765. )
  4766. if sync_type is None:
  4767. pieces = []
  4768. else:
  4769. pieces = [sync_type]
  4770. return self.execute_command("SCRIPT FLUSH", *pieces)
  4771. def script_kill(self) -> ResponseT:
  4772. """
  4773. Kill the currently executing Lua script
  4774. For more information see https://redis.io/commands/script-kill
  4775. """
  4776. return self.execute_command("SCRIPT KILL")
  4777. def script_load(self, script: ScriptTextT) -> ResponseT:
  4778. """
  4779. Load a Lua ``script`` into the script cache. Returns the SHA.
  4780. For more information see https://redis.io/commands/script-load
  4781. """
  4782. return self.execute_command("SCRIPT LOAD", script)
  4783. def register_script(self: "Redis", script: ScriptTextT) -> Script:
  4784. """
  4785. Register a Lua ``script`` specifying the ``keys`` it will touch.
  4786. Returns a Script object that is callable and hides the complexity of
  4787. deal with scripts, keys, and shas. This is the preferred way to work
  4788. with Lua scripts.
  4789. """
  4790. return Script(self, script)
  4791. class AsyncScriptCommands(ScriptCommands):
  4792. async def script_debug(self, *args) -> None:
  4793. return super().script_debug()
  4794. def register_script(self: "AsyncRedis", script: ScriptTextT) -> AsyncScript:
  4795. """
  4796. Register a Lua ``script`` specifying the ``keys`` it will touch.
  4797. Returns a Script object that is callable and hides the complexity of
  4798. deal with scripts, keys, and shas. This is the preferred way to work
  4799. with Lua scripts.
  4800. """
  4801. return AsyncScript(self, script)
  4802. class GeoCommands(CommandsProtocol):
  4803. """
  4804. Redis Geospatial commands.
  4805. see: https://redis.com/redis-best-practices/indexing-patterns/geospatial/
  4806. """
  4807. def geoadd(
  4808. self,
  4809. name: KeyT,
  4810. values: Sequence[EncodableT],
  4811. nx: bool = False,
  4812. xx: bool = False,
  4813. ch: bool = False,
  4814. ) -> ResponseT:
  4815. """
  4816. Add the specified geospatial items to the specified key identified
  4817. by the ``name`` argument. The Geospatial items are given as ordered
  4818. members of the ``values`` argument, each item or place is formed by
  4819. the triad longitude, latitude and name.
  4820. Note: You can use ZREM to remove elements.
  4821. ``nx`` forces ZADD to only create new elements and not to update
  4822. scores for elements that already exist.
  4823. ``xx`` forces ZADD to only update scores of elements that already
  4824. exist. New elements will not be added.
  4825. ``ch`` modifies the return value to be the numbers of elements changed.
  4826. Changed elements include new elements that were added and elements
  4827. whose scores changed.
  4828. For more information see https://redis.io/commands/geoadd
  4829. """
  4830. if nx and xx:
  4831. raise DataError("GEOADD allows either 'nx' or 'xx', not both")
  4832. if len(values) % 3 != 0:
  4833. raise DataError("GEOADD requires places with lon, lat and name values")
  4834. pieces = [name]
  4835. if nx:
  4836. pieces.append("NX")
  4837. if xx:
  4838. pieces.append("XX")
  4839. if ch:
  4840. pieces.append("CH")
  4841. pieces.extend(values)
  4842. return self.execute_command("GEOADD", *pieces)
  4843. def geodist(
  4844. self, name: KeyT, place1: FieldT, place2: FieldT, unit: Union[str, None] = None
  4845. ) -> ResponseT:
  4846. """
  4847. Return the distance between ``place1`` and ``place2`` members of the
  4848. ``name`` key.
  4849. The units must be one of the following : m, km mi, ft. By default
  4850. meters are used.
  4851. For more information see https://redis.io/commands/geodist
  4852. """
  4853. pieces: list[EncodableT] = [name, place1, place2]
  4854. if unit and unit not in ("m", "km", "mi", "ft"):
  4855. raise DataError("GEODIST invalid unit")
  4856. elif unit:
  4857. pieces.append(unit)
  4858. return self.execute_command("GEODIST", *pieces)
  4859. def geohash(self, name: KeyT, *values: FieldT) -> ResponseT:
  4860. """
  4861. Return the geo hash string for each item of ``values`` members of
  4862. the specified key identified by the ``name`` argument.
  4863. For more information see https://redis.io/commands/geohash
  4864. """
  4865. return self.execute_command("GEOHASH", name, *values)
  4866. def geopos(self, name: KeyT, *values: FieldT) -> ResponseT:
  4867. """
  4868. Return the positions of each item of ``values`` as members of
  4869. the specified key identified by the ``name`` argument. Each position
  4870. is represented by the pairs lon and lat.
  4871. For more information see https://redis.io/commands/geopos
  4872. """
  4873. return self.execute_command("GEOPOS", name, *values)
  4874. def georadius(
  4875. self,
  4876. name: KeyT,
  4877. longitude: float,
  4878. latitude: float,
  4879. radius: float,
  4880. unit: Union[str, None] = None,
  4881. withdist: bool = False,
  4882. withcoord: bool = False,
  4883. withhash: bool = False,
  4884. count: Union[int, None] = None,
  4885. sort: Union[str, None] = None,
  4886. store: Union[KeyT, None] = None,
  4887. store_dist: Union[KeyT, None] = None,
  4888. any: bool = False,
  4889. ) -> ResponseT:
  4890. """
  4891. Return the members of the specified key identified by the
  4892. ``name`` argument which are within the borders of the area specified
  4893. with the ``latitude`` and ``longitude`` location and the maximum
  4894. distance from the center specified by the ``radius`` value.
  4895. The units must be one of the following : m, km mi, ft. By default
  4896. ``withdist`` indicates to return the distances of each place.
  4897. ``withcoord`` indicates to return the latitude and longitude of
  4898. each place.
  4899. ``withhash`` indicates to return the geohash string of each place.
  4900. ``count`` indicates to return the number of elements up to N.
  4901. ``sort`` indicates to return the places in a sorted way, ASC for
  4902. nearest to fairest and DESC for fairest to nearest.
  4903. ``store`` indicates to save the places names in a sorted set named
  4904. with a specific key, each element of the destination sorted set is
  4905. populated with the score got from the original geo sorted set.
  4906. ``store_dist`` indicates to save the places names in a sorted set
  4907. named with a specific key, instead of ``store`` the sorted set
  4908. destination score is set with the distance.
  4909. For more information see https://redis.io/commands/georadius
  4910. """
  4911. return self._georadiusgeneric(
  4912. "GEORADIUS",
  4913. name,
  4914. longitude,
  4915. latitude,
  4916. radius,
  4917. unit=unit,
  4918. withdist=withdist,
  4919. withcoord=withcoord,
  4920. withhash=withhash,
  4921. count=count,
  4922. sort=sort,
  4923. store=store,
  4924. store_dist=store_dist,
  4925. any=any,
  4926. )
  4927. def georadiusbymember(
  4928. self,
  4929. name: KeyT,
  4930. member: FieldT,
  4931. radius: float,
  4932. unit: Union[str, None] = None,
  4933. withdist: bool = False,
  4934. withcoord: bool = False,
  4935. withhash: bool = False,
  4936. count: Union[int, None] = None,
  4937. sort: Union[str, None] = None,
  4938. store: Union[KeyT, None] = None,
  4939. store_dist: Union[KeyT, None] = None,
  4940. any: bool = False,
  4941. ) -> ResponseT:
  4942. """
  4943. This command is exactly like ``georadius`` with the sole difference
  4944. that instead of taking, as the center of the area to query, a longitude
  4945. and latitude value, it takes the name of a member already existing
  4946. inside the geospatial index represented by the sorted set.
  4947. For more information see https://redis.io/commands/georadiusbymember
  4948. """
  4949. return self._georadiusgeneric(
  4950. "GEORADIUSBYMEMBER",
  4951. name,
  4952. member,
  4953. radius,
  4954. unit=unit,
  4955. withdist=withdist,
  4956. withcoord=withcoord,
  4957. withhash=withhash,
  4958. count=count,
  4959. sort=sort,
  4960. store=store,
  4961. store_dist=store_dist,
  4962. any=any,
  4963. )
  4964. def _georadiusgeneric(
  4965. self, command: str, *args: EncodableT, **kwargs: Union[EncodableT, None]
  4966. ) -> ResponseT:
  4967. pieces = list(args)
  4968. if kwargs["unit"] and kwargs["unit"] not in ("m", "km", "mi", "ft"):
  4969. raise DataError("GEORADIUS invalid unit")
  4970. elif kwargs["unit"]:
  4971. pieces.append(kwargs["unit"])
  4972. else:
  4973. pieces.append("m")
  4974. if kwargs["any"] and kwargs["count"] is None:
  4975. raise DataError("``any`` can't be provided without ``count``")
  4976. for arg_name, byte_repr in (
  4977. ("withdist", "WITHDIST"),
  4978. ("withcoord", "WITHCOORD"),
  4979. ("withhash", "WITHHASH"),
  4980. ):
  4981. if kwargs[arg_name]:
  4982. pieces.append(byte_repr)
  4983. if kwargs["count"] is not None:
  4984. pieces.extend(["COUNT", kwargs["count"]])
  4985. if kwargs["any"]:
  4986. pieces.append("ANY")
  4987. if kwargs["sort"]:
  4988. if kwargs["sort"] == "ASC":
  4989. pieces.append("ASC")
  4990. elif kwargs["sort"] == "DESC":
  4991. pieces.append("DESC")
  4992. else:
  4993. raise DataError("GEORADIUS invalid sort")
  4994. if kwargs["store"] and kwargs["store_dist"]:
  4995. raise DataError("GEORADIUS store and store_dist cant be set together")
  4996. if kwargs["store"]:
  4997. pieces.extend([b"STORE", kwargs["store"]])
  4998. if kwargs["store_dist"]:
  4999. pieces.extend([b"STOREDIST", kwargs["store_dist"]])
  5000. return self.execute_command(command, *pieces, **kwargs)
  5001. def geosearch(
  5002. self,
  5003. name: KeyT,
  5004. member: Union[FieldT, None] = None,
  5005. longitude: Union[float, None] = None,
  5006. latitude: Union[float, None] = None,
  5007. unit: str = "m",
  5008. radius: Union[float, None] = None,
  5009. width: Union[float, None] = None,
  5010. height: Union[float, None] = None,
  5011. sort: Union[str, None] = None,
  5012. count: Union[int, None] = None,
  5013. any: bool = False,
  5014. withcoord: bool = False,
  5015. withdist: bool = False,
  5016. withhash: bool = False,
  5017. ) -> ResponseT:
  5018. """
  5019. Return the members of specified key identified by the
  5020. ``name`` argument, which are within the borders of the
  5021. area specified by a given shape. This command extends the
  5022. GEORADIUS command, so in addition to searching within circular
  5023. areas, it supports searching within rectangular areas.
  5024. This command should be used in place of the deprecated
  5025. GEORADIUS and GEORADIUSBYMEMBER commands.
  5026. ``member`` Use the position of the given existing
  5027. member in the sorted set. Can't be given with ``longitude``
  5028. and ``latitude``.
  5029. ``longitude`` and ``latitude`` Use the position given by
  5030. this coordinates. Can't be given with ``member``
  5031. ``radius`` Similar to GEORADIUS, search inside circular
  5032. area according the given radius. Can't be given with
  5033. ``height`` and ``width``.
  5034. ``height`` and ``width`` Search inside an axis-aligned
  5035. rectangle, determined by the given height and width.
  5036. Can't be given with ``radius``
  5037. ``unit`` must be one of the following : m, km, mi, ft.
  5038. `m` for meters (the default value), `km` for kilometers,
  5039. `mi` for miles and `ft` for feet.
  5040. ``sort`` indicates to return the places in a sorted way,
  5041. ASC for nearest to furthest and DESC for furthest to nearest.
  5042. ``count`` limit the results to the first count matching items.
  5043. ``any`` is set to True, the command will return as soon as
  5044. enough matches are found. Can't be provided without ``count``
  5045. ``withdist`` indicates to return the distances of each place.
  5046. ``withcoord`` indicates to return the latitude and longitude of
  5047. each place.
  5048. ``withhash`` indicates to return the geohash string of each place.
  5049. For more information see https://redis.io/commands/geosearch
  5050. """
  5051. return self._geosearchgeneric(
  5052. "GEOSEARCH",
  5053. name,
  5054. member=member,
  5055. longitude=longitude,
  5056. latitude=latitude,
  5057. unit=unit,
  5058. radius=radius,
  5059. width=width,
  5060. height=height,
  5061. sort=sort,
  5062. count=count,
  5063. any=any,
  5064. withcoord=withcoord,
  5065. withdist=withdist,
  5066. withhash=withhash,
  5067. store=None,
  5068. store_dist=None,
  5069. )
  5070. def geosearchstore(
  5071. self,
  5072. dest: KeyT,
  5073. name: KeyT,
  5074. member: Union[FieldT, None] = None,
  5075. longitude: Union[float, None] = None,
  5076. latitude: Union[float, None] = None,
  5077. unit: str = "m",
  5078. radius: Union[float, None] = None,
  5079. width: Union[float, None] = None,
  5080. height: Union[float, None] = None,
  5081. sort: Union[str, None] = None,
  5082. count: Union[int, None] = None,
  5083. any: bool = False,
  5084. storedist: bool = False,
  5085. ) -> ResponseT:
  5086. """
  5087. This command is like GEOSEARCH, but stores the result in
  5088. ``dest``. By default, it stores the results in the destination
  5089. sorted set with their geospatial information.
  5090. if ``store_dist`` set to True, the command will stores the
  5091. items in a sorted set populated with their distance from the
  5092. center of the circle or box, as a floating-point number.
  5093. For more information see https://redis.io/commands/geosearchstore
  5094. """
  5095. return self._geosearchgeneric(
  5096. "GEOSEARCHSTORE",
  5097. dest,
  5098. name,
  5099. member=member,
  5100. longitude=longitude,
  5101. latitude=latitude,
  5102. unit=unit,
  5103. radius=radius,
  5104. width=width,
  5105. height=height,
  5106. sort=sort,
  5107. count=count,
  5108. any=any,
  5109. withcoord=None,
  5110. withdist=None,
  5111. withhash=None,
  5112. store=None,
  5113. store_dist=storedist,
  5114. )
  5115. def _geosearchgeneric(
  5116. self, command: str, *args: EncodableT, **kwargs: Union[EncodableT, None]
  5117. ) -> ResponseT:
  5118. pieces = list(args)
  5119. # FROMMEMBER or FROMLONLAT
  5120. if kwargs["member"] is None:
  5121. if kwargs["longitude"] is None or kwargs["latitude"] is None:
  5122. raise DataError("GEOSEARCH must have member or longitude and latitude")
  5123. if kwargs["member"]:
  5124. if kwargs["longitude"] or kwargs["latitude"]:
  5125. raise DataError(
  5126. "GEOSEARCH member and longitude or latitude cant be set together"
  5127. )
  5128. pieces.extend([b"FROMMEMBER", kwargs["member"]])
  5129. if kwargs["longitude"] is not None and kwargs["latitude"] is not None:
  5130. pieces.extend([b"FROMLONLAT", kwargs["longitude"], kwargs["latitude"]])
  5131. # BYRADIUS or BYBOX
  5132. if kwargs["radius"] is None:
  5133. if kwargs["width"] is None or kwargs["height"] is None:
  5134. raise DataError("GEOSEARCH must have radius or width and height")
  5135. if kwargs["unit"] is None:
  5136. raise DataError("GEOSEARCH must have unit")
  5137. if kwargs["unit"].lower() not in ("m", "km", "mi", "ft"):
  5138. raise DataError("GEOSEARCH invalid unit")
  5139. if kwargs["radius"]:
  5140. if kwargs["width"] or kwargs["height"]:
  5141. raise DataError(
  5142. "GEOSEARCH radius and width or height cant be set together"
  5143. )
  5144. pieces.extend([b"BYRADIUS", kwargs["radius"], kwargs["unit"]])
  5145. if kwargs["width"] and kwargs["height"]:
  5146. pieces.extend([b"BYBOX", kwargs["width"], kwargs["height"], kwargs["unit"]])
  5147. # sort
  5148. if kwargs["sort"]:
  5149. if kwargs["sort"].upper() == "ASC":
  5150. pieces.append(b"ASC")
  5151. elif kwargs["sort"].upper() == "DESC":
  5152. pieces.append(b"DESC")
  5153. else:
  5154. raise DataError("GEOSEARCH invalid sort")
  5155. # count any
  5156. if kwargs["count"]:
  5157. pieces.extend([b"COUNT", kwargs["count"]])
  5158. if kwargs["any"]:
  5159. pieces.append(b"ANY")
  5160. elif kwargs["any"]:
  5161. raise DataError("GEOSEARCH ``any`` can't be provided without count")
  5162. # other properties
  5163. for arg_name, byte_repr in (
  5164. ("withdist", b"WITHDIST"),
  5165. ("withcoord", b"WITHCOORD"),
  5166. ("withhash", b"WITHHASH"),
  5167. ("store_dist", b"STOREDIST"),
  5168. ):
  5169. if kwargs[arg_name]:
  5170. pieces.append(byte_repr)
  5171. return self.execute_command(command, *pieces, **kwargs)
  5172. AsyncGeoCommands = GeoCommands
  5173. class ModuleCommands(CommandsProtocol):
  5174. """
  5175. Redis Module commands.
  5176. see: https://redis.io/topics/modules-intro
  5177. """
  5178. def module_load(self, path, *args) -> ResponseT:
  5179. """
  5180. Loads the module from ``path``.
  5181. Passes all ``*args`` to the module, during loading.
  5182. Raises ``ModuleError`` if a module is not found at ``path``.
  5183. For more information see https://redis.io/commands/module-load
  5184. """
  5185. return self.execute_command("MODULE LOAD", path, *args)
  5186. def module_loadex(
  5187. self,
  5188. path: str,
  5189. options: Optional[List[str]] = None,
  5190. args: Optional[List[str]] = None,
  5191. ) -> ResponseT:
  5192. """
  5193. Loads a module from a dynamic library at runtime with configuration directives.
  5194. For more information see https://redis.io/commands/module-loadex
  5195. """
  5196. pieces = []
  5197. if options is not None:
  5198. pieces.append("CONFIG")
  5199. pieces.extend(options)
  5200. if args is not None:
  5201. pieces.append("ARGS")
  5202. pieces.extend(args)
  5203. return self.execute_command("MODULE LOADEX", path, *pieces)
  5204. def module_unload(self, name) -> ResponseT:
  5205. """
  5206. Unloads the module ``name``.
  5207. Raises ``ModuleError`` if ``name`` is not in loaded modules.
  5208. For more information see https://redis.io/commands/module-unload
  5209. """
  5210. return self.execute_command("MODULE UNLOAD", name)
  5211. def module_list(self) -> ResponseT:
  5212. """
  5213. Returns a list of dictionaries containing the name and version of
  5214. all loaded modules.
  5215. For more information see https://redis.io/commands/module-list
  5216. """
  5217. return self.execute_command("MODULE LIST")
  5218. def command_info(self) -> None:
  5219. raise NotImplementedError(
  5220. "COMMAND INFO is intentionally not implemented in the client."
  5221. )
  5222. def command_count(self) -> ResponseT:
  5223. return self.execute_command("COMMAND COUNT")
  5224. def command_getkeys(self, *args) -> ResponseT:
  5225. return self.execute_command("COMMAND GETKEYS", *args)
  5226. def command(self) -> ResponseT:
  5227. return self.execute_command("COMMAND")
  5228. class Script:
  5229. """
  5230. An executable Lua script object returned by ``register_script``
  5231. """
  5232. def __init__(self, registered_client, script):
  5233. self.registered_client = registered_client
  5234. self.script = script
  5235. # Precalculate and store the SHA1 hex digest of the script.
  5236. if isinstance(script, str):
  5237. # We need the encoding from the client in order to generate an
  5238. # accurate byte representation of the script
  5239. encoder = self.get_encoder()
  5240. script = encoder.encode(script)
  5241. self.sha = hashlib.sha1(script).hexdigest()
  5242. def __call__(self, keys=[], args=[], client=None):
  5243. "Execute the script, passing any required ``args``"
  5244. if client is None:
  5245. client = self.registered_client
  5246. args = tuple(keys) + tuple(args)
  5247. # make sure the Redis server knows about the script
  5248. from redis.client import Pipeline
  5249. if isinstance(client, Pipeline):
  5250. # Make sure the pipeline can register the script before executing.
  5251. client.scripts.add(self)
  5252. try:
  5253. return client.evalsha(self.sha, len(keys), *args)
  5254. except NoScriptError:
  5255. # Maybe the client is pointed to a different server than the client
  5256. # that created this instance?
  5257. # Overwrite the sha just in case there was a discrepancy.
  5258. self.sha = client.script_load(self.script)
  5259. return client.evalsha(self.sha, len(keys), *args)
  5260. def get_encoder(self):
  5261. """Get the encoder to encode string scripts into bytes."""
  5262. try:
  5263. return self.registered_client.get_encoder()
  5264. except AttributeError:
  5265. # DEPRECATED
  5266. # In version <=4.1.2, this was the code we used to get the encoder.
  5267. # However, after 4.1.2 we added support for scripting in clustered
  5268. # redis. ClusteredRedis doesn't have a `.connection_pool` attribute
  5269. # so we changed the Script class to use
  5270. # `self.registered_client.get_encoder` (see above).
  5271. # However, that is technically a breaking change, as consumers who
  5272. # use Scripts directly might inject a `registered_client` that
  5273. # doesn't have a `.get_encoder` field. This try/except prevents us
  5274. # from breaking backward-compatibility. Ideally, it would be
  5275. # removed in the next major release.
  5276. return self.registered_client.connection_pool.get_encoder()
  5277. class AsyncModuleCommands(ModuleCommands):
  5278. async def command_info(self) -> None:
  5279. return super().command_info()
  5280. class ClusterCommands(CommandsProtocol):
  5281. """
  5282. Class for Redis Cluster commands
  5283. """
  5284. def cluster(self, cluster_arg, *args, **kwargs) -> ResponseT:
  5285. return self.execute_command(f"CLUSTER {cluster_arg.upper()}", *args, **kwargs)
  5286. def readwrite(self, **kwargs) -> ResponseT:
  5287. """
  5288. Disables read queries for a connection to a Redis Cluster slave node.
  5289. For more information see https://redis.io/commands/readwrite
  5290. """
  5291. return self.execute_command("READWRITE", **kwargs)
  5292. def readonly(self, **kwargs) -> ResponseT:
  5293. """
  5294. Enables read queries for a connection to a Redis Cluster replica node.
  5295. For more information see https://redis.io/commands/readonly
  5296. """
  5297. return self.execute_command("READONLY", **kwargs)
  5298. AsyncClusterCommands = ClusterCommands
  5299. class FunctionCommands:
  5300. """
  5301. Redis Function commands
  5302. """
  5303. def function_load(
  5304. self, code: str, replace: Optional[bool] = False
  5305. ) -> Union[Awaitable[str], str]:
  5306. """
  5307. Load a library to Redis.
  5308. :param code: the source code (must start with
  5309. Shebang statement that provides a metadata about the library)
  5310. :param replace: changes the behavior to overwrite the existing library
  5311. with the new contents.
  5312. Return the library name that was loaded.
  5313. For more information see https://redis.io/commands/function-load
  5314. """
  5315. pieces = ["REPLACE"] if replace else []
  5316. pieces.append(code)
  5317. return self.execute_command("FUNCTION LOAD", *pieces)
  5318. def function_delete(self, library: str) -> Union[Awaitable[str], str]:
  5319. """
  5320. Delete the library called ``library`` and all its functions.
  5321. For more information see https://redis.io/commands/function-delete
  5322. """
  5323. return self.execute_command("FUNCTION DELETE", library)
  5324. def function_flush(self, mode: str = "SYNC") -> Union[Awaitable[str], str]:
  5325. """
  5326. Deletes all the libraries.
  5327. For more information see https://redis.io/commands/function-flush
  5328. """
  5329. return self.execute_command("FUNCTION FLUSH", mode)
  5330. def function_list(
  5331. self, library: Optional[str] = "*", withcode: Optional[bool] = False
  5332. ) -> Union[Awaitable[List], List]:
  5333. """
  5334. Return information about the functions and libraries.
  5335. :param library: pecify a pattern for matching library names
  5336. :param withcode: cause the server to include the libraries source
  5337. implementation in the reply
  5338. """
  5339. args = ["LIBRARYNAME", library]
  5340. if withcode:
  5341. args.append("WITHCODE")
  5342. return self.execute_command("FUNCTION LIST", *args)
  5343. def _fcall(
  5344. self, command: str, function, numkeys: int, *keys_and_args: Optional[List]
  5345. ) -> Union[Awaitable[str], str]:
  5346. return self.execute_command(command, function, numkeys, *keys_and_args)
  5347. def fcall(
  5348. self, function, numkeys: int, *keys_and_args: Optional[List]
  5349. ) -> Union[Awaitable[str], str]:
  5350. """
  5351. Invoke a function.
  5352. For more information see https://redis.io/commands/fcall
  5353. """
  5354. return self._fcall("FCALL", function, numkeys, *keys_and_args)
  5355. def fcall_ro(
  5356. self, function, numkeys: int, *keys_and_args: Optional[List]
  5357. ) -> Union[Awaitable[str], str]:
  5358. """
  5359. This is a read-only variant of the FCALL command that cannot
  5360. execute commands that modify data.
  5361. For more information see https://redis.io/commands/fcal_ro
  5362. """
  5363. return self._fcall("FCALL_RO", function, numkeys, *keys_and_args)
  5364. def function_dump(self) -> Union[Awaitable[str], str]:
  5365. """
  5366. Return the serialized payload of loaded libraries.
  5367. For more information see https://redis.io/commands/function-dump
  5368. """
  5369. from redis.client import NEVER_DECODE
  5370. options = {}
  5371. options[NEVER_DECODE] = []
  5372. return self.execute_command("FUNCTION DUMP", **options)
  5373. def function_restore(
  5374. self, payload: str, policy: Optional[str] = "APPEND"
  5375. ) -> Union[Awaitable[str], str]:
  5376. """
  5377. Restore libraries from the serialized ``payload``.
  5378. You can use the optional policy argument to provide a policy
  5379. for handling existing libraries.
  5380. For more information see https://redis.io/commands/function-restore
  5381. """
  5382. return self.execute_command("FUNCTION RESTORE", payload, policy)
  5383. def function_kill(self) -> Union[Awaitable[str], str]:
  5384. """
  5385. Kill a function that is currently executing.
  5386. For more information see https://redis.io/commands/function-kill
  5387. """
  5388. return self.execute_command("FUNCTION KILL")
  5389. def function_stats(self) -> Union[Awaitable[List], List]:
  5390. """
  5391. Return information about the function that's currently running
  5392. and information about the available execution engines.
  5393. For more information see https://redis.io/commands/function-stats
  5394. """
  5395. return self.execute_command("FUNCTION STATS")
  5396. AsyncFunctionCommands = FunctionCommands
  5397. class GearsCommands:
  5398. def tfunction_load(
  5399. self, lib_code: str, replace: bool = False, config: Union[str, None] = None
  5400. ) -> ResponseT:
  5401. """
  5402. Load a new library to RedisGears.
  5403. ``lib_code`` - the library code.
  5404. ``config`` - a string representation of a JSON object
  5405. that will be provided to the library on load time,
  5406. for more information refer to
  5407. https://github.com/RedisGears/RedisGears/blob/master/docs/function_advance_topics.md#library-configuration
  5408. ``replace`` - an optional argument, instructs RedisGears to replace the
  5409. function if its already exists
  5410. For more information see https://redis.io/commands/tfunction-load/
  5411. """
  5412. pieces = []
  5413. if replace:
  5414. pieces.append("REPLACE")
  5415. if config is not None:
  5416. pieces.extend(["CONFIG", config])
  5417. pieces.append(lib_code)
  5418. return self.execute_command("TFUNCTION LOAD", *pieces)
  5419. def tfunction_delete(self, lib_name: str) -> ResponseT:
  5420. """
  5421. Delete a library from RedisGears.
  5422. ``lib_name`` the library name to delete.
  5423. For more information see https://redis.io/commands/tfunction-delete/
  5424. """
  5425. return self.execute_command("TFUNCTION DELETE", lib_name)
  5426. def tfunction_list(
  5427. self,
  5428. with_code: bool = False,
  5429. verbose: int = 0,
  5430. lib_name: Union[str, None] = None,
  5431. ) -> ResponseT:
  5432. """
  5433. List the functions with additional information about each function.
  5434. ``with_code`` Show libraries code.
  5435. ``verbose`` output verbosity level, higher number will increase verbosity level
  5436. ``lib_name`` specifying a library name (can be used multiple times to show multiple libraries in a single command) # noqa
  5437. For more information see https://redis.io/commands/tfunction-list/
  5438. """
  5439. pieces = []
  5440. if with_code:
  5441. pieces.append("WITHCODE")
  5442. if verbose >= 1 and verbose <= 3:
  5443. pieces.append("v" * verbose)
  5444. else:
  5445. raise DataError("verbose can be 1, 2 or 3")
  5446. if lib_name is not None:
  5447. pieces.append("LIBRARY")
  5448. pieces.append(lib_name)
  5449. return self.execute_command("TFUNCTION LIST", *pieces)
  5450. def _tfcall(
  5451. self,
  5452. lib_name: str,
  5453. func_name: str,
  5454. keys: KeysT = None,
  5455. _async: bool = False,
  5456. *args: List,
  5457. ) -> ResponseT:
  5458. pieces = [f"{lib_name}.{func_name}"]
  5459. if keys is not None:
  5460. pieces.append(len(keys))
  5461. pieces.extend(keys)
  5462. else:
  5463. pieces.append(0)
  5464. if args is not None:
  5465. pieces.extend(args)
  5466. if _async:
  5467. return self.execute_command("TFCALLASYNC", *pieces)
  5468. return self.execute_command("TFCALL", *pieces)
  5469. def tfcall(
  5470. self,
  5471. lib_name: str,
  5472. func_name: str,
  5473. keys: KeysT = None,
  5474. *args: List,
  5475. ) -> ResponseT:
  5476. """
  5477. Invoke a function.
  5478. ``lib_name`` - the library name contains the function.
  5479. ``func_name`` - the function name to run.
  5480. ``keys`` - the keys that will be touched by the function.
  5481. ``args`` - Additional argument to pass to the function.
  5482. For more information see https://redis.io/commands/tfcall/
  5483. """
  5484. return self._tfcall(lib_name, func_name, keys, False, *args)
  5485. def tfcall_async(
  5486. self,
  5487. lib_name: str,
  5488. func_name: str,
  5489. keys: KeysT = None,
  5490. *args: List,
  5491. ) -> ResponseT:
  5492. """
  5493. Invoke an async function (coroutine).
  5494. ``lib_name`` - the library name contains the function.
  5495. ``func_name`` - the function name to run.
  5496. ``keys`` - the keys that will be touched by the function.
  5497. ``args`` - Additional argument to pass to the function.
  5498. For more information see https://redis.io/commands/tfcall/
  5499. """
  5500. return self._tfcall(lib_name, func_name, keys, True, *args)
  5501. AsyncGearsCommands = GearsCommands
  5502. class DataAccessCommands(
  5503. BasicKeyCommands,
  5504. HyperlogCommands,
  5505. HashCommands,
  5506. GeoCommands,
  5507. ListCommands,
  5508. ScanCommands,
  5509. SetCommands,
  5510. StreamCommands,
  5511. SortedSetCommands,
  5512. ):
  5513. """
  5514. A class containing all of the implemented data access redis commands.
  5515. This class is to be used as a mixin for synchronous Redis clients.
  5516. """
  5517. class AsyncDataAccessCommands(
  5518. AsyncBasicKeyCommands,
  5519. AsyncHyperlogCommands,
  5520. AsyncHashCommands,
  5521. AsyncGeoCommands,
  5522. AsyncListCommands,
  5523. AsyncScanCommands,
  5524. AsyncSetCommands,
  5525. AsyncStreamCommands,
  5526. AsyncSortedSetCommands,
  5527. ):
  5528. """
  5529. A class containing all of the implemented data access redis commands.
  5530. This class is to be used as a mixin for asynchronous Redis clients.
  5531. """
  5532. class CoreCommands(
  5533. ACLCommands,
  5534. ClusterCommands,
  5535. DataAccessCommands,
  5536. ManagementCommands,
  5537. ModuleCommands,
  5538. PubSubCommands,
  5539. ScriptCommands,
  5540. FunctionCommands,
  5541. GearsCommands,
  5542. ):
  5543. """
  5544. A class containing all of the implemented redis commands. This class is
  5545. to be used as a mixin for synchronous Redis clients.
  5546. """
  5547. class AsyncCoreCommands(
  5548. AsyncACLCommands,
  5549. AsyncClusterCommands,
  5550. AsyncDataAccessCommands,
  5551. AsyncManagementCommands,
  5552. AsyncModuleCommands,
  5553. AsyncPubSubCommands,
  5554. AsyncScriptCommands,
  5555. AsyncFunctionCommands,
  5556. AsyncGearsCommands,
  5557. ):
  5558. """
  5559. A class containing all of the implemented redis commands. This class is
  5560. to be used as a mixin for asynchronous Redis clients.
  5561. """