client.py 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699
  1. from __future__ import with_statement
  2. from itertools import chain
  3. import datetime
  4. import sys
  5. import warnings
  6. import time
  7. import threading
  8. import time as mod_time
  9. from redis._compat import (b, basestring, bytes, imap, iteritems, iterkeys,
  10. itervalues, izip, long, nativestr, unicode,
  11. safe_unicode)
  12. from redis.connection import (ConnectionPool, UnixDomainSocketConnection,
  13. SSLConnection, Token)
  14. from redis.lock import Lock, LuaLock
  15. from redis.exceptions import (
  16. ConnectionError,
  17. DataError,
  18. ExecAbortError,
  19. NoScriptError,
  20. PubSubError,
  21. RedisError,
  22. ResponseError,
  23. TimeoutError,
  24. WatchError,
  25. )
  26. SYM_EMPTY = b('')
  27. def list_or_args(keys, args):
  28. # returns a single list combining keys and args
  29. try:
  30. iter(keys)
  31. # a string or bytes instance can be iterated, but indicates
  32. # keys wasn't passed as a list
  33. if isinstance(keys, (basestring, bytes)):
  34. keys = [keys]
  35. except TypeError:
  36. keys = [keys]
  37. if args:
  38. keys.extend(args)
  39. return keys
  40. def timestamp_to_datetime(response):
  41. "Converts a unix timestamp to a Python datetime object"
  42. if not response:
  43. return None
  44. try:
  45. response = int(response)
  46. except ValueError:
  47. return None
  48. return datetime.datetime.fromtimestamp(response)
  49. def string_keys_to_dict(key_string, callback):
  50. return dict.fromkeys(key_string.split(), callback)
  51. def dict_merge(*dicts):
  52. merged = {}
  53. for d in dicts:
  54. merged.update(d)
  55. return merged
  56. def parse_debug_object(response):
  57. "Parse the results of Redis's DEBUG OBJECT command into a Python dict"
  58. # The 'type' of the object is the first item in the response, but isn't
  59. # prefixed with a name
  60. response = nativestr(response)
  61. response = 'type:' + response
  62. response = dict([kv.split(':') for kv in response.split()])
  63. # parse some expected int values from the string response
  64. # note: this cmd isn't spec'd so these may not appear in all redis versions
  65. int_fields = ('refcount', 'serializedlength', 'lru', 'lru_seconds_idle')
  66. for field in int_fields:
  67. if field in response:
  68. response[field] = int(response[field])
  69. return response
  70. def parse_object(response, infotype):
  71. "Parse the results of an OBJECT command"
  72. if infotype in ('idletime', 'refcount'):
  73. return int_or_none(response)
  74. return response
  75. def parse_info(response):
  76. "Parse the result of Redis's INFO command into a Python dict"
  77. info = {}
  78. response = nativestr(response)
  79. def get_value(value):
  80. if ',' not in value or '=' not in value:
  81. try:
  82. if '.' in value:
  83. return float(value)
  84. else:
  85. return int(value)
  86. except ValueError:
  87. return value
  88. else:
  89. sub_dict = {}
  90. for item in value.split(','):
  91. k, v = item.rsplit('=', 1)
  92. sub_dict[k] = get_value(v)
  93. return sub_dict
  94. for line in response.splitlines():
  95. if line and not line.startswith('#'):
  96. if line.find(':') != -1:
  97. key, value = line.split(':', 1)
  98. info[key] = get_value(value)
  99. else:
  100. # if the line isn't splittable, append it to the "__raw__" key
  101. info.setdefault('__raw__', []).append(line)
  102. return info
  103. SENTINEL_STATE_TYPES = {
  104. 'can-failover-its-master': int,
  105. 'config-epoch': int,
  106. 'down-after-milliseconds': int,
  107. 'failover-timeout': int,
  108. 'info-refresh': int,
  109. 'last-hello-message': int,
  110. 'last-ok-ping-reply': int,
  111. 'last-ping-reply': int,
  112. 'last-ping-sent': int,
  113. 'master-link-down-time': int,
  114. 'master-port': int,
  115. 'num-other-sentinels': int,
  116. 'num-slaves': int,
  117. 'o-down-time': int,
  118. 'pending-commands': int,
  119. 'parallel-syncs': int,
  120. 'port': int,
  121. 'quorum': int,
  122. 'role-reported-time': int,
  123. 's-down-time': int,
  124. 'slave-priority': int,
  125. 'slave-repl-offset': int,
  126. 'voted-leader-epoch': int
  127. }
  128. def parse_sentinel_state(item):
  129. result = pairs_to_dict_typed(item, SENTINEL_STATE_TYPES)
  130. flags = set(result['flags'].split(','))
  131. for name, flag in (('is_master', 'master'), ('is_slave', 'slave'),
  132. ('is_sdown', 's_down'), ('is_odown', 'o_down'),
  133. ('is_sentinel', 'sentinel'),
  134. ('is_disconnected', 'disconnected'),
  135. ('is_master_down', 'master_down')):
  136. result[name] = flag in flags
  137. return result
  138. def parse_sentinel_master(response):
  139. return parse_sentinel_state(imap(nativestr, response))
  140. def parse_sentinel_masters(response):
  141. result = {}
  142. for item in response:
  143. state = parse_sentinel_state(imap(nativestr, item))
  144. result[state['name']] = state
  145. return result
  146. def parse_sentinel_slaves_and_sentinels(response):
  147. return [parse_sentinel_state(imap(nativestr, item)) for item in response]
  148. def parse_sentinel_get_master(response):
  149. return response and (response[0], int(response[1])) or None
  150. def pairs_to_dict(response):
  151. "Create a dict given a list of key/value pairs"
  152. it = iter(response)
  153. return dict(izip(it, it))
  154. def pairs_to_dict_typed(response, type_info):
  155. it = iter(response)
  156. result = {}
  157. for key, value in izip(it, it):
  158. if key in type_info:
  159. try:
  160. value = type_info[key](value)
  161. except:
  162. # if for some reason the value can't be coerced, just use
  163. # the string value
  164. pass
  165. result[key] = value
  166. return result
  167. def zset_score_pairs(response, **options):
  168. """
  169. If ``withscores`` is specified in the options, return the response as
  170. a list of (value, score) pairs
  171. """
  172. if not response or not options['withscores']:
  173. return response
  174. score_cast_func = options.get('score_cast_func', float)
  175. it = iter(response)
  176. return list(izip(it, imap(score_cast_func, it)))
  177. def sort_return_tuples(response, **options):
  178. """
  179. If ``groups`` is specified, return the response as a list of
  180. n-element tuples with n being the value found in options['groups']
  181. """
  182. if not response or not options['groups']:
  183. return response
  184. n = options['groups']
  185. return list(izip(*[response[i::n] for i in range(n)]))
  186. def int_or_none(response):
  187. if response is None:
  188. return None
  189. return int(response)
  190. def float_or_none(response):
  191. if response is None:
  192. return None
  193. return float(response)
  194. def bool_ok(response):
  195. return nativestr(response) == 'OK'
  196. def parse_client_list(response, **options):
  197. clients = []
  198. for c in nativestr(response).splitlines():
  199. clients.append(dict([pair.split('=') for pair in c.split(' ')]))
  200. return clients
  201. def parse_config_get(response, **options):
  202. response = [nativestr(i) if i is not None else None for i in response]
  203. return response and pairs_to_dict(response) or {}
  204. def parse_scan(response, **options):
  205. cursor, r = response
  206. return long(cursor), r
  207. def parse_hscan(response, **options):
  208. cursor, r = response
  209. return long(cursor), r and pairs_to_dict(r) or {}
  210. def parse_zscan(response, **options):
  211. score_cast_func = options.get('score_cast_func', float)
  212. cursor, r = response
  213. it = iter(r)
  214. return long(cursor), list(izip(it, imap(score_cast_func, it)))
  215. def parse_slowlog_get(response, **options):
  216. return [{
  217. 'id': item[0],
  218. 'start_time': int(item[1]),
  219. 'duration': int(item[2]),
  220. 'command': b(' ').join(item[3])
  221. } for item in response]
  222. class StrictRedis(object):
  223. """
  224. Implementation of the Redis protocol.
  225. This abstract class provides a Python interface to all Redis commands
  226. and an implementation of the Redis protocol.
  227. Connection and Pipeline derive from this, implementing how
  228. the commands are sent and received to the Redis server
  229. """
  230. RESPONSE_CALLBACKS = dict_merge(
  231. string_keys_to_dict(
  232. 'AUTH EXISTS EXPIRE EXPIREAT HEXISTS HMSET MOVE MSETNX PERSIST '
  233. 'PSETEX RENAMENX SISMEMBER SMOVE SETEX SETNX',
  234. bool
  235. ),
  236. string_keys_to_dict(
  237. 'BITCOUNT BITPOS DECRBY DEL GETBIT HDEL HLEN INCRBY LINSERT LLEN '
  238. 'LPUSHX PFADD PFCOUNT RPUSHX SADD SCARD SDIFFSTORE SETBIT '
  239. 'SETRANGE SINTERSTORE SREM STRLEN SUNIONSTORE ZADD ZCARD '
  240. 'ZLEXCOUNT ZREM ZREMRANGEBYLEX ZREMRANGEBYRANK ZREMRANGEBYSCORE',
  241. int
  242. ),
  243. string_keys_to_dict('INCRBYFLOAT HINCRBYFLOAT', float),
  244. string_keys_to_dict(
  245. # these return OK, or int if redis-server is >=1.3.4
  246. 'LPUSH RPUSH',
  247. lambda r: isinstance(r, long) and r or nativestr(r) == 'OK'
  248. ),
  249. string_keys_to_dict('SORT', sort_return_tuples),
  250. string_keys_to_dict('ZSCORE ZINCRBY', float_or_none),
  251. string_keys_to_dict(
  252. 'FLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE RENAME '
  253. 'SAVE SELECT SHUTDOWN SLAVEOF WATCH UNWATCH',
  254. bool_ok
  255. ),
  256. string_keys_to_dict('BLPOP BRPOP', lambda r: r and tuple(r) or None),
  257. string_keys_to_dict(
  258. 'SDIFF SINTER SMEMBERS SUNION',
  259. lambda r: r and set(r) or set()
  260. ),
  261. string_keys_to_dict(
  262. 'ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCORE',
  263. zset_score_pairs
  264. ),
  265. string_keys_to_dict('ZRANK ZREVRANK', int_or_none),
  266. string_keys_to_dict('BGREWRITEAOF BGSAVE', lambda r: True),
  267. {
  268. 'CLIENT GETNAME': lambda r: r and nativestr(r),
  269. 'CLIENT KILL': bool_ok,
  270. 'CLIENT LIST': parse_client_list,
  271. 'CLIENT SETNAME': bool_ok,
  272. 'CONFIG GET': parse_config_get,
  273. 'CONFIG RESETSTAT': bool_ok,
  274. 'CONFIG SET': bool_ok,
  275. 'DEBUG OBJECT': parse_debug_object,
  276. 'HGETALL': lambda r: r and pairs_to_dict(r) or {},
  277. 'HSCAN': parse_hscan,
  278. 'INFO': parse_info,
  279. 'LASTSAVE': timestamp_to_datetime,
  280. 'OBJECT': parse_object,
  281. 'PING': lambda r: nativestr(r) == 'PONG',
  282. 'RANDOMKEY': lambda r: r and r or None,
  283. 'SCAN': parse_scan,
  284. 'SCRIPT EXISTS': lambda r: list(imap(bool, r)),
  285. 'SCRIPT FLUSH': bool_ok,
  286. 'SCRIPT KILL': bool_ok,
  287. 'SCRIPT LOAD': nativestr,
  288. 'SENTINEL GET-MASTER-ADDR-BY-NAME': parse_sentinel_get_master,
  289. 'SENTINEL MASTER': parse_sentinel_master,
  290. 'SENTINEL MASTERS': parse_sentinel_masters,
  291. 'SENTINEL MONITOR': bool_ok,
  292. 'SENTINEL REMOVE': bool_ok,
  293. 'SENTINEL SENTINELS': parse_sentinel_slaves_and_sentinels,
  294. 'SENTINEL SET': bool_ok,
  295. 'SENTINEL SLAVES': parse_sentinel_slaves_and_sentinels,
  296. 'SET': lambda r: r and nativestr(r) == 'OK',
  297. 'SLOWLOG GET': parse_slowlog_get,
  298. 'SLOWLOG LEN': int,
  299. 'SLOWLOG RESET': bool_ok,
  300. 'SSCAN': parse_scan,
  301. 'TIME': lambda x: (int(x[0]), int(x[1])),
  302. 'ZSCAN': parse_zscan
  303. }
  304. )
  305. @classmethod
  306. def from_url(cls, url, db=None, **kwargs):
  307. """
  308. Return a Redis client object configured from the given URL.
  309. For example::
  310. redis://[:password]@localhost:6379/0
  311. unix://[:password]@/path/to/socket.sock?db=0
  312. There are several ways to specify a database number. The parse function
  313. will return the first specified option:
  314. 1. A ``db`` querystring option, e.g. redis://localhost?db=0
  315. 2. If using the redis:// scheme, the path argument of the url, e.g.
  316. redis://localhost/0
  317. 3. The ``db`` argument to this function.
  318. If none of these options are specified, db=0 is used.
  319. Any additional querystring arguments and keyword arguments will be
  320. passed along to the ConnectionPool class's initializer. In the case
  321. of conflicting arguments, querystring arguments always win.
  322. """
  323. connection_pool = ConnectionPool.from_url(url, db=db, **kwargs)
  324. return cls(connection_pool=connection_pool)
  325. def __init__(self, host='localhost', port=6379,
  326. db=0, password=None, socket_timeout=None,
  327. socket_connect_timeout=None,
  328. socket_keepalive=None, socket_keepalive_options=None,
  329. connection_pool=None, unix_socket_path=None,
  330. encoding='utf-8', encoding_errors='strict',
  331. charset=None, errors=None,
  332. decode_responses=False, retry_on_timeout=False,
  333. ssl=False, ssl_keyfile=None, ssl_certfile=None,
  334. ssl_cert_reqs=None, ssl_ca_certs=None,
  335. max_connections=None):
  336. if not connection_pool:
  337. if charset is not None:
  338. warnings.warn(DeprecationWarning(
  339. '"charset" is deprecated. Use "encoding" instead'))
  340. encoding = charset
  341. if errors is not None:
  342. warnings.warn(DeprecationWarning(
  343. '"errors" is deprecated. Use "encoding_errors" instead'))
  344. encoding_errors = errors
  345. kwargs = {
  346. 'db': db,
  347. 'password': password,
  348. 'socket_timeout': socket_timeout,
  349. 'encoding': encoding,
  350. 'encoding_errors': encoding_errors,
  351. 'decode_responses': decode_responses,
  352. 'retry_on_timeout': retry_on_timeout,
  353. 'max_connections': max_connections
  354. }
  355. # based on input, setup appropriate connection args
  356. if unix_socket_path is not None:
  357. kwargs.update({
  358. 'path': unix_socket_path,
  359. 'connection_class': UnixDomainSocketConnection
  360. })
  361. else:
  362. # TCP specific options
  363. kwargs.update({
  364. 'host': host,
  365. 'port': port,
  366. 'socket_connect_timeout': socket_connect_timeout,
  367. 'socket_keepalive': socket_keepalive,
  368. 'socket_keepalive_options': socket_keepalive_options,
  369. })
  370. if ssl:
  371. kwargs.update({
  372. 'connection_class': SSLConnection,
  373. 'ssl_keyfile': ssl_keyfile,
  374. 'ssl_certfile': ssl_certfile,
  375. 'ssl_cert_reqs': ssl_cert_reqs,
  376. 'ssl_ca_certs': ssl_ca_certs,
  377. })
  378. connection_pool = ConnectionPool(**kwargs)
  379. self.connection_pool = connection_pool
  380. self._use_lua_lock = None
  381. self.response_callbacks = self.__class__.RESPONSE_CALLBACKS.copy()
  382. def __repr__(self):
  383. return "%s<%s>" % (type(self).__name__, repr(self.connection_pool))
  384. def set_response_callback(self, command, callback):
  385. "Set a custom Response Callback"
  386. self.response_callbacks[command] = callback
  387. def pipeline(self, transaction=True, shard_hint=None):
  388. """
  389. Return a new pipeline object that can queue multiple commands for
  390. later execution. ``transaction`` indicates whether all commands
  391. should be executed atomically. Apart from making a group of operations
  392. atomic, pipelines are useful for reducing the back-and-forth overhead
  393. between the client and server.
  394. """
  395. return StrictPipeline(
  396. self.connection_pool,
  397. self.response_callbacks,
  398. transaction,
  399. shard_hint)
  400. def transaction(self, func, *watches, **kwargs):
  401. """
  402. Convenience method for executing the callable `func` as a transaction
  403. while watching all keys specified in `watches`. The 'func' callable
  404. should expect a single argument which is a Pipeline object.
  405. """
  406. shard_hint = kwargs.pop('shard_hint', None)
  407. value_from_callable = kwargs.pop('value_from_callable', False)
  408. watch_delay = kwargs.pop('watch_delay', None)
  409. with self.pipeline(True, shard_hint) as pipe:
  410. while 1:
  411. try:
  412. if watches:
  413. pipe.watch(*watches)
  414. func_value = func(pipe)
  415. exec_value = pipe.execute()
  416. return func_value if value_from_callable else exec_value
  417. except WatchError:
  418. if watch_delay is not None and watch_delay > 0:
  419. time.sleep(watch_delay)
  420. continue
  421. def lock(self, name, timeout=None, sleep=0.1, blocking_timeout=None,
  422. lock_class=None, thread_local=True):
  423. """
  424. Return a new Lock object using key ``name`` that mimics
  425. the behavior of threading.Lock.
  426. If specified, ``timeout`` indicates a maximum life for the lock.
  427. By default, it will remain locked until release() is called.
  428. ``sleep`` indicates the amount of time to sleep per loop iteration
  429. when the lock is in blocking mode and another client is currently
  430. holding the lock.
  431. ``blocking_timeout`` indicates the maximum amount of time in seconds to
  432. spend trying to acquire the lock. A value of ``None`` indicates
  433. continue trying forever. ``blocking_timeout`` can be specified as a
  434. float or integer, both representing the number of seconds to wait.
  435. ``lock_class`` forces the specified lock implementation.
  436. ``thread_local`` indicates whether the lock token is placed in
  437. thread-local storage. By default, the token is placed in thread local
  438. storage so that a thread only sees its token, not a token set by
  439. another thread. Consider the following timeline:
  440. time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
  441. thread-1 sets the token to "abc"
  442. time: 1, thread-2 blocks trying to acquire `my-lock` using the
  443. Lock instance.
  444. time: 5, thread-1 has not yet completed. redis expires the lock
  445. key.
  446. time: 5, thread-2 acquired `my-lock` now that it's available.
  447. thread-2 sets the token to "xyz"
  448. time: 6, thread-1 finishes its work and calls release(). if the
  449. token is *not* stored in thread local storage, then
  450. thread-1 would see the token value as "xyz" and would be
  451. able to successfully release the thread-2's lock.
  452. In some use cases it's necessary to disable thread local storage. For
  453. example, if you have code where one thread acquires a lock and passes
  454. that lock instance to a worker thread to release later. If thread
  455. local storage isn't disabled in this case, the worker thread won't see
  456. the token set by the thread that acquired the lock. Our assumption
  457. is that these cases aren't common and as such default to using
  458. thread local storage. """
  459. if lock_class is None:
  460. if self._use_lua_lock is None:
  461. # the first time .lock() is called, determine if we can use
  462. # Lua by attempting to register the necessary scripts
  463. try:
  464. LuaLock.register_scripts(self)
  465. self._use_lua_lock = True
  466. except ResponseError:
  467. self._use_lua_lock = False
  468. lock_class = self._use_lua_lock and LuaLock or Lock
  469. return lock_class(self, name, timeout=timeout, sleep=sleep,
  470. blocking_timeout=blocking_timeout,
  471. thread_local=thread_local)
  472. def pubsub(self, **kwargs):
  473. """
  474. Return a Publish/Subscribe object. With this object, you can
  475. subscribe to channels and listen for messages that get published to
  476. them.
  477. """
  478. return PubSub(self.connection_pool, **kwargs)
  479. # COMMAND EXECUTION AND PROTOCOL PARSING
  480. def execute_command(self, *args, **options):
  481. "Execute a command and return a parsed response"
  482. pool = self.connection_pool
  483. command_name = args[0]
  484. connection = pool.get_connection(command_name, **options)
  485. try:
  486. connection.send_command(*args)
  487. return self.parse_response(connection, command_name, **options)
  488. except (ConnectionError, TimeoutError) as e:
  489. connection.disconnect()
  490. if not connection.retry_on_timeout and isinstance(e, TimeoutError):
  491. raise
  492. connection.send_command(*args)
  493. return self.parse_response(connection, command_name, **options)
  494. finally:
  495. pool.release(connection)
  496. def parse_response(self, connection, command_name, **options):
  497. "Parses a response from the Redis server"
  498. response = connection.read_response()
  499. if command_name in self.response_callbacks:
  500. return self.response_callbacks[command_name](response, **options)
  501. return response
  502. # SERVER INFORMATION
  503. def bgrewriteaof(self):
  504. "Tell the Redis server to rewrite the AOF file from data in memory."
  505. return self.execute_command('BGREWRITEAOF')
  506. def bgsave(self):
  507. """
  508. Tell the Redis server to save its data to disk. Unlike save(),
  509. this method is asynchronous and returns immediately.
  510. """
  511. return self.execute_command('BGSAVE')
  512. def client_kill(self, address):
  513. "Disconnects the client at ``address`` (ip:port)"
  514. return self.execute_command('CLIENT KILL', address)
  515. def client_list(self):
  516. "Returns a list of currently connected clients"
  517. return self.execute_command('CLIENT LIST')
  518. def client_getname(self):
  519. "Returns the current connection name"
  520. return self.execute_command('CLIENT GETNAME')
  521. def client_setname(self, name):
  522. "Sets the current connection name"
  523. return self.execute_command('CLIENT SETNAME', name)
  524. def config_get(self, pattern="*"):
  525. "Return a dictionary of configuration based on the ``pattern``"
  526. return self.execute_command('CONFIG GET', pattern)
  527. def config_set(self, name, value):
  528. "Set config item ``name`` with ``value``"
  529. return self.execute_command('CONFIG SET', name, value)
  530. def config_resetstat(self):
  531. "Reset runtime statistics"
  532. return self.execute_command('CONFIG RESETSTAT')
  533. def config_rewrite(self):
  534. "Rewrite config file with the minimal change to reflect running config"
  535. return self.execute_command('CONFIG REWRITE')
  536. def dbsize(self):
  537. "Returns the number of keys in the current database"
  538. return self.execute_command('DBSIZE')
  539. def debug_object(self, key):
  540. "Returns version specific meta information about a given key"
  541. return self.execute_command('DEBUG OBJECT', key)
  542. def echo(self, value):
  543. "Echo the string back from the server"
  544. return self.execute_command('ECHO', value)
  545. def flushall(self):
  546. "Delete all keys in all databases on the current host"
  547. return self.execute_command('FLUSHALL')
  548. def flushdb(self):
  549. "Delete all keys in the current database"
  550. return self.execute_command('FLUSHDB')
  551. def info(self, section=None):
  552. """
  553. Returns a dictionary containing information about the Redis server
  554. The ``section`` option can be used to select a specific section
  555. of information
  556. The section option is not supported by older versions of Redis Server,
  557. and will generate ResponseError
  558. """
  559. if section is None:
  560. return self.execute_command('INFO')
  561. else:
  562. return self.execute_command('INFO', section)
  563. def lastsave(self):
  564. """
  565. Return a Python datetime object representing the last time the
  566. Redis database was saved to disk
  567. """
  568. return self.execute_command('LASTSAVE')
  569. def object(self, infotype, key):
  570. "Return the encoding, idletime, or refcount about the key"
  571. return self.execute_command('OBJECT', infotype, key, infotype=infotype)
  572. def ping(self):
  573. "Ping the Redis server"
  574. return self.execute_command('PING')
  575. def save(self):
  576. """
  577. Tell the Redis server to save its data to disk,
  578. blocking until the save is complete
  579. """
  580. return self.execute_command('SAVE')
  581. def sentinel(self, *args):
  582. "Redis Sentinel's SENTINEL command."
  583. warnings.warn(
  584. DeprecationWarning('Use the individual sentinel_* methods'))
  585. def sentinel_get_master_addr_by_name(self, service_name):
  586. "Returns a (host, port) pair for the given ``service_name``"
  587. return self.execute_command('SENTINEL GET-MASTER-ADDR-BY-NAME',
  588. service_name)
  589. def sentinel_master(self, service_name):
  590. "Returns a dictionary containing the specified masters state."
  591. return self.execute_command('SENTINEL MASTER', service_name)
  592. def sentinel_masters(self):
  593. "Returns a list of dictionaries containing each master's state."
  594. return self.execute_command('SENTINEL MASTERS')
  595. def sentinel_monitor(self, name, ip, port, quorum):
  596. "Add a new master to Sentinel to be monitored"
  597. return self.execute_command('SENTINEL MONITOR', name, ip, port, quorum)
  598. def sentinel_remove(self, name):
  599. "Remove a master from Sentinel's monitoring"
  600. return self.execute_command('SENTINEL REMOVE', name)
  601. def sentinel_sentinels(self, service_name):
  602. "Returns a list of sentinels for ``service_name``"
  603. return self.execute_command('SENTINEL SENTINELS', service_name)
  604. def sentinel_set(self, name, option, value):
  605. "Set Sentinel monitoring parameters for a given master"
  606. return self.execute_command('SENTINEL SET', name, option, value)
  607. def sentinel_slaves(self, service_name):
  608. "Returns a list of slaves for ``service_name``"
  609. return self.execute_command('SENTINEL SLAVES', service_name)
  610. def shutdown(self):
  611. "Shutdown the server"
  612. try:
  613. self.execute_command('SHUTDOWN')
  614. except ConnectionError:
  615. # a ConnectionError here is expected
  616. return
  617. raise RedisError("SHUTDOWN seems to have failed.")
  618. def slaveof(self, host=None, port=None):
  619. """
  620. Set the server to be a replicated slave of the instance identified
  621. by the ``host`` and ``port``. If called without arguments, the
  622. instance is promoted to a master instead.
  623. """
  624. if host is None and port is None:
  625. return self.execute_command('SLAVEOF', Token('NO'), Token('ONE'))
  626. return self.execute_command('SLAVEOF', host, port)
  627. def slowlog_get(self, num=None):
  628. """
  629. Get the entries from the slowlog. If ``num`` is specified, get the
  630. most recent ``num`` items.
  631. """
  632. args = ['SLOWLOG GET']
  633. if num is not None:
  634. args.append(num)
  635. return self.execute_command(*args)
  636. def slowlog_len(self):
  637. "Get the number of items in the slowlog"
  638. return self.execute_command('SLOWLOG LEN')
  639. def slowlog_reset(self):
  640. "Remove all items in the slowlog"
  641. return self.execute_command('SLOWLOG RESET')
  642. def time(self):
  643. """
  644. Returns the server time as a 2-item tuple of ints:
  645. (seconds since epoch, microseconds into this second).
  646. """
  647. return self.execute_command('TIME')
  648. def wait(self, num_replicas, timeout):
  649. """
  650. Redis synchronous replication
  651. That returns the number of replicas that processed the query when
  652. we finally have at least ``num_replicas``, or when the ``timeout`` was
  653. reached.
  654. """
  655. return self.execute_command('WAIT', num_replicas, timeout)
  656. # BASIC KEY COMMANDS
  657. def append(self, key, value):
  658. """
  659. Appends the string ``value`` to the value at ``key``. If ``key``
  660. doesn't already exist, create it with a value of ``value``.
  661. Returns the new length of the value at ``key``.
  662. """
  663. return self.execute_command('APPEND', key, value)
  664. def bitcount(self, key, start=None, end=None):
  665. """
  666. Returns the count of set bits in the value of ``key``. Optional
  667. ``start`` and ``end`` paramaters indicate which bytes to consider
  668. """
  669. params = [key]
  670. if start is not None and end is not None:
  671. params.append(start)
  672. params.append(end)
  673. elif (start is not None and end is None) or \
  674. (end is not None and start is None):
  675. raise RedisError("Both start and end must be specified")
  676. return self.execute_command('BITCOUNT', *params)
  677. def bitop(self, operation, dest, *keys):
  678. """
  679. Perform a bitwise operation using ``operation`` between ``keys`` and
  680. store the result in ``dest``.
  681. """
  682. return self.execute_command('BITOP', operation, dest, *keys)
  683. def bitpos(self, key, bit, start=None, end=None):
  684. """
  685. Return the position of the first bit set to 1 or 0 in a string.
  686. ``start`` and ``end`` difines search range. The range is interpreted
  687. as a range of bytes and not a range of bits, so start=0 and end=2
  688. means to look at the first three bytes.
  689. """
  690. if bit not in (0, 1):
  691. raise RedisError('bit must be 0 or 1')
  692. params = [key, bit]
  693. start is not None and params.append(start)
  694. if start is not None and end is not None:
  695. params.append(end)
  696. elif start is None and end is not None:
  697. raise RedisError("start argument is not set, "
  698. "when end is specified")
  699. return self.execute_command('BITPOS', *params)
  700. def decr(self, name, amount=1):
  701. """
  702. Decrements the value of ``key`` by ``amount``. If no key exists,
  703. the value will be initialized as 0 - ``amount``
  704. """
  705. return self.execute_command('DECRBY', name, amount)
  706. def delete(self, *names):
  707. "Delete one or more keys specified by ``names``"
  708. return self.execute_command('DEL', *names)
  709. def __delitem__(self, name):
  710. self.delete(name)
  711. def dump(self, name):
  712. """
  713. Return a serialized version of the value stored at the specified key.
  714. If key does not exist a nil bulk reply is returned.
  715. """
  716. return self.execute_command('DUMP', name)
  717. def exists(self, name):
  718. "Returns a boolean indicating whether key ``name`` exists"
  719. return self.execute_command('EXISTS', name)
  720. __contains__ = exists
  721. def expire(self, name, time):
  722. """
  723. Set an expire flag on key ``name`` for ``time`` seconds. ``time``
  724. can be represented by an integer or a Python timedelta object.
  725. """
  726. if isinstance(time, datetime.timedelta):
  727. time = time.seconds + time.days * 24 * 3600
  728. return self.execute_command('EXPIRE', name, time)
  729. def expireat(self, name, when):
  730. """
  731. Set an expire flag on key ``name``. ``when`` can be represented
  732. as an integer indicating unix time or a Python datetime object.
  733. """
  734. if isinstance(when, datetime.datetime):
  735. when = int(mod_time.mktime(when.timetuple()))
  736. return self.execute_command('EXPIREAT', name, when)
  737. def get(self, name):
  738. """
  739. Return the value at key ``name``, or None if the key doesn't exist
  740. """
  741. return self.execute_command('GET', name)
  742. def __getitem__(self, name):
  743. """
  744. Return the value at key ``name``, raises a KeyError if the key
  745. doesn't exist.
  746. """
  747. value = self.get(name)
  748. if value:
  749. return value
  750. raise KeyError(name)
  751. def getbit(self, name, offset):
  752. "Returns a boolean indicating the value of ``offset`` in ``name``"
  753. return self.execute_command('GETBIT', name, offset)
  754. def getrange(self, key, start, end):
  755. """
  756. Returns the substring of the string value stored at ``key``,
  757. determined by the offsets ``start`` and ``end`` (both are inclusive)
  758. """
  759. return self.execute_command('GETRANGE', key, start, end)
  760. def getset(self, name, value):
  761. """
  762. Sets the value at key ``name`` to ``value``
  763. and returns the old value at key ``name`` atomically.
  764. """
  765. return self.execute_command('GETSET', name, value)
  766. def incr(self, name, amount=1):
  767. """
  768. Increments the value of ``key`` by ``amount``. If no key exists,
  769. the value will be initialized as ``amount``
  770. """
  771. return self.execute_command('INCRBY', name, amount)
  772. def incrby(self, name, amount=1):
  773. """
  774. Increments the value of ``key`` by ``amount``. If no key exists,
  775. the value will be initialized as ``amount``
  776. """
  777. # An alias for ``incr()``, because it is already implemented
  778. # as INCRBY redis command.
  779. return self.incr(name, amount)
  780. def incrbyfloat(self, name, amount=1.0):
  781. """
  782. Increments the value at key ``name`` by floating ``amount``.
  783. If no key exists, the value will be initialized as ``amount``
  784. """
  785. return self.execute_command('INCRBYFLOAT', name, amount)
  786. def keys(self, pattern='*'):
  787. "Returns a list of keys matching ``pattern``"
  788. return self.execute_command('KEYS', pattern)
  789. def mget(self, keys, *args):
  790. """
  791. Returns a list of values ordered identically to ``keys``
  792. """
  793. args = list_or_args(keys, args)
  794. return self.execute_command('MGET', *args)
  795. def mset(self, *args, **kwargs):
  796. """
  797. Sets key/values based on a mapping. Mapping can be supplied as a single
  798. dictionary argument or as kwargs.
  799. """
  800. if args:
  801. if len(args) != 1 or not isinstance(args[0], dict):
  802. raise RedisError('MSET requires **kwargs or a single dict arg')
  803. kwargs.update(args[0])
  804. items = []
  805. for pair in iteritems(kwargs):
  806. items.extend(pair)
  807. return self.execute_command('MSET', *items)
  808. def msetnx(self, *args, **kwargs):
  809. """
  810. Sets key/values based on a mapping if none of the keys are already set.
  811. Mapping can be supplied as a single dictionary argument or as kwargs.
  812. Returns a boolean indicating if the operation was successful.
  813. """
  814. if args:
  815. if len(args) != 1 or not isinstance(args[0], dict):
  816. raise RedisError('MSETNX requires **kwargs or a single '
  817. 'dict arg')
  818. kwargs.update(args[0])
  819. items = []
  820. for pair in iteritems(kwargs):
  821. items.extend(pair)
  822. return self.execute_command('MSETNX', *items)
  823. def move(self, name, db):
  824. "Moves the key ``name`` to a different Redis database ``db``"
  825. return self.execute_command('MOVE', name, db)
  826. def persist(self, name):
  827. "Removes an expiration on ``name``"
  828. return self.execute_command('PERSIST', name)
  829. def pexpire(self, name, time):
  830. """
  831. Set an expire flag on key ``name`` for ``time`` milliseconds.
  832. ``time`` can be represented by an integer or a Python timedelta
  833. object.
  834. """
  835. if isinstance(time, datetime.timedelta):
  836. ms = int(time.microseconds / 1000)
  837. time = (time.seconds + time.days * 24 * 3600) * 1000 + ms
  838. return self.execute_command('PEXPIRE', name, time)
  839. def pexpireat(self, name, when):
  840. """
  841. Set an expire flag on key ``name``. ``when`` can be represented
  842. as an integer representing unix time in milliseconds (unix time * 1000)
  843. or a Python datetime object.
  844. """
  845. if isinstance(when, datetime.datetime):
  846. ms = int(when.microsecond / 1000)
  847. when = int(mod_time.mktime(when.timetuple())) * 1000 + ms
  848. return self.execute_command('PEXPIREAT', name, when)
  849. def psetex(self, name, time_ms, value):
  850. """
  851. Set the value of key ``name`` to ``value`` that expires in ``time_ms``
  852. milliseconds. ``time_ms`` can be represented by an integer or a Python
  853. timedelta object
  854. """
  855. if isinstance(time_ms, datetime.timedelta):
  856. ms = int(time_ms.microseconds / 1000)
  857. time_ms = (time_ms.seconds + time_ms.days * 24 * 3600) * 1000 + ms
  858. return self.execute_command('PSETEX', name, time_ms, value)
  859. def pttl(self, name):
  860. "Returns the number of milliseconds until the key ``name`` will expire"
  861. return self.execute_command('PTTL', name)
  862. def randomkey(self):
  863. "Returns the name of a random key"
  864. return self.execute_command('RANDOMKEY')
  865. def rename(self, src, dst):
  866. """
  867. Rename key ``src`` to ``dst``
  868. """
  869. return self.execute_command('RENAME', src, dst)
  870. def renamenx(self, src, dst):
  871. "Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist"
  872. return self.execute_command('RENAMENX', src, dst)
  873. def restore(self, name, ttl, value):
  874. """
  875. Create a key using the provided serialized value, previously obtained
  876. using DUMP.
  877. """
  878. return self.execute_command('RESTORE', name, ttl, value)
  879. def set(self, name, value, ex=None, px=None, nx=False, xx=False):
  880. """
  881. Set the value at key ``name`` to ``value``
  882. ``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.
  883. ``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.
  884. ``nx`` if set to True, set the value at key ``name`` to ``value`` if it
  885. does not already exist.
  886. ``xx`` if set to True, set the value at key ``name`` to ``value`` if it
  887. already exists.
  888. """
  889. pieces = [name, value]
  890. if ex:
  891. pieces.append('EX')
  892. if isinstance(ex, datetime.timedelta):
  893. ex = ex.seconds + ex.days * 24 * 3600
  894. pieces.append(ex)
  895. if px:
  896. pieces.append('PX')
  897. if isinstance(px, datetime.timedelta):
  898. ms = int(px.microseconds / 1000)
  899. px = (px.seconds + px.days * 24 * 3600) * 1000 + ms
  900. pieces.append(px)
  901. if nx:
  902. pieces.append('NX')
  903. if xx:
  904. pieces.append('XX')
  905. return self.execute_command('SET', *pieces)
  906. def __setitem__(self, name, value):
  907. self.set(name, value)
  908. def setbit(self, name, offset, value):
  909. """
  910. Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
  911. indicating the previous value of ``offset``.
  912. """
  913. value = value and 1 or 0
  914. return self.execute_command('SETBIT', name, offset, value)
  915. def setex(self, name, time, value):
  916. """
  917. Set the value of key ``name`` to ``value`` that expires in ``time``
  918. seconds. ``time`` can be represented by an integer or a Python
  919. timedelta object.
  920. """
  921. if isinstance(time, datetime.timedelta):
  922. time = time.seconds + time.days * 24 * 3600
  923. return self.execute_command('SETEX', name, time, value)
  924. def setnx(self, name, value):
  925. "Set the value of key ``name`` to ``value`` if key doesn't exist"
  926. return self.execute_command('SETNX', name, value)
  927. def setrange(self, name, offset, value):
  928. """
  929. Overwrite bytes in the value of ``name`` starting at ``offset`` with
  930. ``value``. If ``offset`` plus the length of ``value`` exceeds the
  931. length of the original value, the new value will be larger than before.
  932. If ``offset`` exceeds the length of the original value, null bytes
  933. will be used to pad between the end of the previous value and the start
  934. of what's being injected.
  935. Returns the length of the new string.
  936. """
  937. return self.execute_command('SETRANGE', name, offset, value)
  938. def strlen(self, name):
  939. "Return the number of bytes stored in the value of ``name``"
  940. return self.execute_command('STRLEN', name)
  941. def substr(self, name, start, end=-1):
  942. """
  943. Return a substring of the string at key ``name``. ``start`` and ``end``
  944. are 0-based integers specifying the portion of the string to return.
  945. """
  946. return self.execute_command('SUBSTR', name, start, end)
  947. def ttl(self, name):
  948. "Returns the number of seconds until the key ``name`` will expire"
  949. return self.execute_command('TTL', name)
  950. def type(self, name):
  951. "Returns the type of key ``name``"
  952. return self.execute_command('TYPE', name)
  953. def watch(self, *names):
  954. """
  955. Watches the values at keys ``names``, or None if the key doesn't exist
  956. """
  957. warnings.warn(DeprecationWarning('Call WATCH from a Pipeline object'))
  958. def unwatch(self):
  959. """
  960. Unwatches the value at key ``name``, or None of the key doesn't exist
  961. """
  962. warnings.warn(
  963. DeprecationWarning('Call UNWATCH from a Pipeline object'))
  964. # LIST COMMANDS
  965. def blpop(self, keys, timeout=0):
  966. """
  967. LPOP a value off of the first non-empty list
  968. named in the ``keys`` list.
  969. If none of the lists in ``keys`` has a value to LPOP, then block
  970. for ``timeout`` seconds, or until a value gets pushed on to one
  971. of the lists.
  972. If timeout is 0, then block indefinitely.
  973. """
  974. if timeout is None:
  975. timeout = 0
  976. if isinstance(keys, basestring):
  977. keys = [keys]
  978. else:
  979. keys = list(keys)
  980. keys.append(timeout)
  981. return self.execute_command('BLPOP', *keys)
  982. def brpop(self, keys, timeout=0):
  983. """
  984. RPOP a value off of the first non-empty list
  985. named in the ``keys`` list.
  986. If none of the lists in ``keys`` has a value to LPOP, then block
  987. for ``timeout`` seconds, or until a value gets pushed on to one
  988. of the lists.
  989. If timeout is 0, then block indefinitely.
  990. """
  991. if timeout is None:
  992. timeout = 0
  993. if isinstance(keys, basestring):
  994. keys = [keys]
  995. else:
  996. keys = list(keys)
  997. keys.append(timeout)
  998. return self.execute_command('BRPOP', *keys)
  999. def brpoplpush(self, src, dst, timeout=0):
  1000. """
  1001. Pop a value off the tail of ``src``, push it on the head of ``dst``
  1002. and then return it.
  1003. This command blocks until a value is in ``src`` or until ``timeout``
  1004. seconds elapse, whichever is first. A ``timeout`` value of 0 blocks
  1005. forever.
  1006. """
  1007. if timeout is None:
  1008. timeout = 0
  1009. return self.execute_command('BRPOPLPUSH', src, dst, timeout)
  1010. def lindex(self, name, index):
  1011. """
  1012. Return the item from list ``name`` at position ``index``
  1013. Negative indexes are supported and will return an item at the
  1014. end of the list
  1015. """
  1016. return self.execute_command('LINDEX', name, index)
  1017. def linsert(self, name, where, refvalue, value):
  1018. """
  1019. Insert ``value`` in list ``name`` either immediately before or after
  1020. [``where``] ``refvalue``
  1021. Returns the new length of the list on success or -1 if ``refvalue``
  1022. is not in the list.
  1023. """
  1024. return self.execute_command('LINSERT', name, where, refvalue, value)
  1025. def llen(self, name):
  1026. "Return the length of the list ``name``"
  1027. return self.execute_command('LLEN', name)
  1028. def lpop(self, name):
  1029. "Remove and return the first item of the list ``name``"
  1030. return self.execute_command('LPOP', name)
  1031. def lpush(self, name, *values):
  1032. "Push ``values`` onto the head of the list ``name``"
  1033. return self.execute_command('LPUSH', name, *values)
  1034. def lpushx(self, name, value):
  1035. "Push ``value`` onto the head of the list ``name`` if ``name`` exists"
  1036. return self.execute_command('LPUSHX', name, value)
  1037. def lrange(self, name, start, end):
  1038. """
  1039. Return a slice of the list ``name`` between
  1040. position ``start`` and ``end``
  1041. ``start`` and ``end`` can be negative numbers just like
  1042. Python slicing notation
  1043. """
  1044. return self.execute_command('LRANGE', name, start, end)
  1045. def lrem(self, name, count, value):
  1046. """
  1047. Remove the first ``count`` occurrences of elements equal to ``value``
  1048. from the list stored at ``name``.
  1049. The count argument influences the operation in the following ways:
  1050. count > 0: Remove elements equal to value moving from head to tail.
  1051. count < 0: Remove elements equal to value moving from tail to head.
  1052. count = 0: Remove all elements equal to value.
  1053. """
  1054. return self.execute_command('LREM', name, count, value)
  1055. def lset(self, name, index, value):
  1056. "Set ``position`` of list ``name`` to ``value``"
  1057. return self.execute_command('LSET', name, index, value)
  1058. def ltrim(self, name, start, end):
  1059. """
  1060. Trim the list ``name``, removing all values not within the slice
  1061. between ``start`` and ``end``
  1062. ``start`` and ``end`` can be negative numbers just like
  1063. Python slicing notation
  1064. """
  1065. return self.execute_command('LTRIM', name, start, end)
  1066. def rpop(self, name):
  1067. "Remove and return the last item of the list ``name``"
  1068. return self.execute_command('RPOP', name)
  1069. def rpoplpush(self, src, dst):
  1070. """
  1071. RPOP a value off of the ``src`` list and atomically LPUSH it
  1072. on to the ``dst`` list. Returns the value.
  1073. """
  1074. return self.execute_command('RPOPLPUSH', src, dst)
  1075. def rpush(self, name, *values):
  1076. "Push ``values`` onto the tail of the list ``name``"
  1077. return self.execute_command('RPUSH', name, *values)
  1078. def rpushx(self, name, value):
  1079. "Push ``value`` onto the tail of the list ``name`` if ``name`` exists"
  1080. return self.execute_command('RPUSHX', name, value)
  1081. def sort(self, name, start=None, num=None, by=None, get=None,
  1082. desc=False, alpha=False, store=None, groups=False):
  1083. """
  1084. Sort and return the list, set or sorted set at ``name``.
  1085. ``start`` and ``num`` allow for paging through the sorted data
  1086. ``by`` allows using an external key to weight and sort the items.
  1087. Use an "*" to indicate where in the key the item value is located
  1088. ``get`` allows for returning items from external keys rather than the
  1089. sorted data itself. Use an "*" to indicate where int he key
  1090. the item value is located
  1091. ``desc`` allows for reversing the sort
  1092. ``alpha`` allows for sorting lexicographically rather than numerically
  1093. ``store`` allows for storing the result of the sort into
  1094. the key ``store``
  1095. ``groups`` if set to True and if ``get`` contains at least two
  1096. elements, sort will return a list of tuples, each containing the
  1097. values fetched from the arguments to ``get``.
  1098. """
  1099. if (start is not None and num is None) or \
  1100. (num is not None and start is None):
  1101. raise RedisError("``start`` and ``num`` must both be specified")
  1102. pieces = [name]
  1103. if by is not None:
  1104. pieces.append(Token('BY'))
  1105. pieces.append(by)
  1106. if start is not None and num is not None:
  1107. pieces.append(Token('LIMIT'))
  1108. pieces.append(start)
  1109. pieces.append(num)
  1110. if get is not None:
  1111. # If get is a string assume we want to get a single value.
  1112. # Otherwise assume it's an interable and we want to get multiple
  1113. # values. We can't just iterate blindly because strings are
  1114. # iterable.
  1115. if isinstance(get, basestring):
  1116. pieces.append(Token('GET'))
  1117. pieces.append(get)
  1118. else:
  1119. for g in get:
  1120. pieces.append(Token('GET'))
  1121. pieces.append(g)
  1122. if desc:
  1123. pieces.append(Token('DESC'))
  1124. if alpha:
  1125. pieces.append(Token('ALPHA'))
  1126. if store is not None:
  1127. pieces.append(Token('STORE'))
  1128. pieces.append(store)
  1129. if groups:
  1130. if not get or isinstance(get, basestring) or len(get) < 2:
  1131. raise DataError('when using "groups" the "get" argument '
  1132. 'must be specified and contain at least '
  1133. 'two keys')
  1134. options = {'groups': len(get) if groups else None}
  1135. return self.execute_command('SORT', *pieces, **options)
  1136. # SCAN COMMANDS
  1137. def scan(self, cursor=0, match=None, count=None):
  1138. """
  1139. Incrementally return lists of key names. Also return a cursor
  1140. indicating the scan position.
  1141. ``match`` allows for filtering the keys by pattern
  1142. ``count`` allows for hint the minimum number of returns
  1143. """
  1144. pieces = [cursor]
  1145. if match is not None:
  1146. pieces.extend([Token('MATCH'), match])
  1147. if count is not None:
  1148. pieces.extend([Token('COUNT'), count])
  1149. return self.execute_command('SCAN', *pieces)
  1150. def scan_iter(self, match=None, count=None):
  1151. """
  1152. Make an iterator using the SCAN command so that the client doesn't
  1153. need to remember the cursor position.
  1154. ``match`` allows for filtering the keys by pattern
  1155. ``count`` allows for hint the minimum number of returns
  1156. """
  1157. cursor = '0'
  1158. while cursor != 0:
  1159. cursor, data = self.scan(cursor=cursor, match=match, count=count)
  1160. for item in data:
  1161. yield item
  1162. def sscan(self, name, cursor=0, match=None, count=None):
  1163. """
  1164. Incrementally return lists of elements in a set. Also return a cursor
  1165. indicating the scan position.
  1166. ``match`` allows for filtering the keys by pattern
  1167. ``count`` allows for hint the minimum number of returns
  1168. """
  1169. pieces = [name, cursor]
  1170. if match is not None:
  1171. pieces.extend([Token('MATCH'), match])
  1172. if count is not None:
  1173. pieces.extend([Token('COUNT'), count])
  1174. return self.execute_command('SSCAN', *pieces)
  1175. def sscan_iter(self, name, match=None, count=None):
  1176. """
  1177. Make an iterator using the SSCAN command so that the client doesn't
  1178. need to remember the cursor position.
  1179. ``match`` allows for filtering the keys by pattern
  1180. ``count`` allows for hint the minimum number of returns
  1181. """
  1182. cursor = '0'
  1183. while cursor != 0:
  1184. cursor, data = self.sscan(name, cursor=cursor,
  1185. match=match, count=count)
  1186. for item in data:
  1187. yield item
  1188. def hscan(self, name, cursor=0, match=None, count=None):
  1189. """
  1190. Incrementally return key/value slices in a hash. Also return a cursor
  1191. indicating the scan position.
  1192. ``match`` allows for filtering the keys by pattern
  1193. ``count`` allows for hint the minimum number of returns
  1194. """
  1195. pieces = [name, cursor]
  1196. if match is not None:
  1197. pieces.extend([Token('MATCH'), match])
  1198. if count is not None:
  1199. pieces.extend([Token('COUNT'), count])
  1200. return self.execute_command('HSCAN', *pieces)
  1201. def hscan_iter(self, name, match=None, count=None):
  1202. """
  1203. Make an iterator using the HSCAN command so that the client doesn't
  1204. need to remember the cursor position.
  1205. ``match`` allows for filtering the keys by pattern
  1206. ``count`` allows for hint the minimum number of returns
  1207. """
  1208. cursor = '0'
  1209. while cursor != 0:
  1210. cursor, data = self.hscan(name, cursor=cursor,
  1211. match=match, count=count)
  1212. for item in data.items():
  1213. yield item
  1214. def zscan(self, name, cursor=0, match=None, count=None,
  1215. score_cast_func=float):
  1216. """
  1217. Incrementally return lists of elements in a sorted set. Also return a
  1218. cursor indicating the scan position.
  1219. ``match`` allows for filtering the keys by pattern
  1220. ``count`` allows for hint the minimum number of returns
  1221. ``score_cast_func`` a callable used to cast the score return value
  1222. """
  1223. pieces = [name, cursor]
  1224. if match is not None:
  1225. pieces.extend([Token('MATCH'), match])
  1226. if count is not None:
  1227. pieces.extend([Token('COUNT'), count])
  1228. options = {'score_cast_func': score_cast_func}
  1229. return self.execute_command('ZSCAN', *pieces, **options)
  1230. def zscan_iter(self, name, match=None, count=None,
  1231. score_cast_func=float):
  1232. """
  1233. Make an iterator using the ZSCAN command so that the client doesn't
  1234. need to remember the cursor position.
  1235. ``match`` allows for filtering the keys by pattern
  1236. ``count`` allows for hint the minimum number of returns
  1237. ``score_cast_func`` a callable used to cast the score return value
  1238. """
  1239. cursor = '0'
  1240. while cursor != 0:
  1241. cursor, data = self.zscan(name, cursor=cursor, match=match,
  1242. count=count,
  1243. score_cast_func=score_cast_func)
  1244. for item in data:
  1245. yield item
  1246. # SET COMMANDS
  1247. def sadd(self, name, *values):
  1248. "Add ``value(s)`` to set ``name``"
  1249. return self.execute_command('SADD', name, *values)
  1250. def scard(self, name):
  1251. "Return the number of elements in set ``name``"
  1252. return self.execute_command('SCARD', name)
  1253. def sdiff(self, keys, *args):
  1254. "Return the difference of sets specified by ``keys``"
  1255. args = list_or_args(keys, args)
  1256. return self.execute_command('SDIFF', *args)
  1257. def sdiffstore(self, dest, keys, *args):
  1258. """
  1259. Store the difference of sets specified by ``keys`` into a new
  1260. set named ``dest``. Returns the number of keys in the new set.
  1261. """
  1262. args = list_or_args(keys, args)
  1263. return self.execute_command('SDIFFSTORE', dest, *args)
  1264. def sinter(self, keys, *args):
  1265. "Return the intersection of sets specified by ``keys``"
  1266. args = list_or_args(keys, args)
  1267. return self.execute_command('SINTER', *args)
  1268. def sinterstore(self, dest, keys, *args):
  1269. """
  1270. Store the intersection of sets specified by ``keys`` into a new
  1271. set named ``dest``. Returns the number of keys in the new set.
  1272. """
  1273. args = list_or_args(keys, args)
  1274. return self.execute_command('SINTERSTORE', dest, *args)
  1275. def sismember(self, name, value):
  1276. "Return a boolean indicating if ``value`` is a member of set ``name``"
  1277. return self.execute_command('SISMEMBER', name, value)
  1278. def smembers(self, name):
  1279. "Return all members of the set ``name``"
  1280. return self.execute_command('SMEMBERS', name)
  1281. def smove(self, src, dst, value):
  1282. "Move ``value`` from set ``src`` to set ``dst`` atomically"
  1283. return self.execute_command('SMOVE', src, dst, value)
  1284. def spop(self, name):
  1285. "Remove and return a random member of set ``name``"
  1286. return self.execute_command('SPOP', name)
  1287. def srandmember(self, name, number=None):
  1288. """
  1289. If ``number`` is None, returns a random member of set ``name``.
  1290. If ``number`` is supplied, returns a list of ``number`` random
  1291. memebers of set ``name``. Note this is only available when running
  1292. Redis 2.6+.
  1293. """
  1294. args = number and [number] or []
  1295. return self.execute_command('SRANDMEMBER', name, *args)
  1296. def srem(self, name, *values):
  1297. "Remove ``values`` from set ``name``"
  1298. return self.execute_command('SREM', name, *values)
  1299. def sunion(self, keys, *args):
  1300. "Return the union of sets specified by ``keys``"
  1301. args = list_or_args(keys, args)
  1302. return self.execute_command('SUNION', *args)
  1303. def sunionstore(self, dest, keys, *args):
  1304. """
  1305. Store the union of sets specified by ``keys`` into a new
  1306. set named ``dest``. Returns the number of keys in the new set.
  1307. """
  1308. args = list_or_args(keys, args)
  1309. return self.execute_command('SUNIONSTORE', dest, *args)
  1310. # SORTED SET COMMANDS
  1311. def zadd(self, name, *args, **kwargs):
  1312. """
  1313. Set any number of score, element-name pairs to the key ``name``. Pairs
  1314. can be specified in two ways:
  1315. As *args, in the form of: score1, name1, score2, name2, ...
  1316. or as **kwargs, in the form of: name1=score1, name2=score2, ...
  1317. The following example would add four values to the 'my-key' key:
  1318. redis.zadd('my-key', 1.1, 'name1', 2.2, 'name2', name3=3.3, name4=4.4)
  1319. """
  1320. pieces = []
  1321. if args:
  1322. if len(args) % 2 != 0:
  1323. raise RedisError("ZADD requires an equal number of "
  1324. "values and scores")
  1325. pieces.extend(args)
  1326. for pair in iteritems(kwargs):
  1327. pieces.append(pair[1])
  1328. pieces.append(pair[0])
  1329. return self.execute_command('ZADD', name, *pieces)
  1330. def zcard(self, name):
  1331. "Return the number of elements in the sorted set ``name``"
  1332. return self.execute_command('ZCARD', name)
  1333. def zcount(self, name, min, max):
  1334. """
  1335. Returns the number of elements in the sorted set at key ``name`` with
  1336. a score between ``min`` and ``max``.
  1337. """
  1338. return self.execute_command('ZCOUNT', name, min, max)
  1339. def zincrby(self, name, value, amount=1):
  1340. "Increment the score of ``value`` in sorted set ``name`` by ``amount``"
  1341. return self.execute_command('ZINCRBY', name, amount, value)
  1342. def zinterstore(self, dest, keys, aggregate=None):
  1343. """
  1344. Intersect multiple sorted sets specified by ``keys`` into
  1345. a new sorted set, ``dest``. Scores in the destination will be
  1346. aggregated based on the ``aggregate``, or SUM if none is provided.
  1347. """
  1348. return self._zaggregate('ZINTERSTORE', dest, keys, aggregate)
  1349. def zlexcount(self, name, min, max):
  1350. """
  1351. Return the number of items in the sorted set ``name`` between the
  1352. lexicographical range ``min`` and ``max``.
  1353. """
  1354. return self.execute_command('ZLEXCOUNT', name, min, max)
  1355. def zrange(self, name, start, end, desc=False, withscores=False,
  1356. score_cast_func=float):
  1357. """
  1358. Return a range of values from sorted set ``name`` between
  1359. ``start`` and ``end`` sorted in ascending order.
  1360. ``start`` and ``end`` can be negative, indicating the end of the range.
  1361. ``desc`` a boolean indicating whether to sort the results descendingly
  1362. ``withscores`` indicates to return the scores along with the values.
  1363. The return type is a list of (value, score) pairs
  1364. ``score_cast_func`` a callable used to cast the score return value
  1365. """
  1366. if desc:
  1367. return self.zrevrange(name, start, end, withscores,
  1368. score_cast_func)
  1369. pieces = ['ZRANGE', name, start, end]
  1370. if withscores:
  1371. pieces.append(Token('WITHSCORES'))
  1372. options = {
  1373. 'withscores': withscores,
  1374. 'score_cast_func': score_cast_func
  1375. }
  1376. return self.execute_command(*pieces, **options)
  1377. def zrangebylex(self, name, min, max, start=None, num=None):
  1378. """
  1379. Return the lexicographical range of values from sorted set ``name``
  1380. between ``min`` and ``max``.
  1381. If ``start`` and ``num`` are specified, then return a slice of the
  1382. range.
  1383. """
  1384. if (start is not None and num is None) or \
  1385. (num is not None and start is None):
  1386. raise RedisError("``start`` and ``num`` must both be specified")
  1387. pieces = ['ZRANGEBYLEX', name, min, max]
  1388. if start is not None and num is not None:
  1389. pieces.extend([Token('LIMIT'), start, num])
  1390. return self.execute_command(*pieces)
  1391. def zrevrangebylex(self, name, max, min, start=None, num=None):
  1392. """
  1393. Return the reversed lexicographical range of values from sorted set
  1394. ``name`` between ``max`` and ``min``.
  1395. If ``start`` and ``num`` are specified, then return a slice of the
  1396. range.
  1397. """
  1398. if (start is not None and num is None) or \
  1399. (num is not None and start is None):
  1400. raise RedisError("``start`` and ``num`` must both be specified")
  1401. pieces = ['ZREVRANGEBYLEX', name, max, min]
  1402. if start is not None and num is not None:
  1403. pieces.extend([Token('LIMIT'), start, num])
  1404. return self.execute_command(*pieces)
  1405. def zrangebyscore(self, name, min, max, start=None, num=None,
  1406. withscores=False, score_cast_func=float):
  1407. """
  1408. Return a range of values from the sorted set ``name`` with scores
  1409. between ``min`` and ``max``.
  1410. If ``start`` and ``num`` are specified, then return a slice
  1411. of the range.
  1412. ``withscores`` indicates to return the scores along with the values.
  1413. The return type is a list of (value, score) pairs
  1414. `score_cast_func`` a callable used to cast the score return value
  1415. """
  1416. if (start is not None and num is None) or \
  1417. (num is not None and start is None):
  1418. raise RedisError("``start`` and ``num`` must both be specified")
  1419. pieces = ['ZRANGEBYSCORE', name, min, max]
  1420. if start is not None and num is not None:
  1421. pieces.extend([Token('LIMIT'), start, num])
  1422. if withscores:
  1423. pieces.append(Token('WITHSCORES'))
  1424. options = {
  1425. 'withscores': withscores,
  1426. 'score_cast_func': score_cast_func
  1427. }
  1428. return self.execute_command(*pieces, **options)
  1429. def zrank(self, name, value):
  1430. """
  1431. Returns a 0-based value indicating the rank of ``value`` in sorted set
  1432. ``name``
  1433. """
  1434. return self.execute_command('ZRANK', name, value)
  1435. def zrem(self, name, *values):
  1436. "Remove member ``values`` from sorted set ``name``"
  1437. return self.execute_command('ZREM', name, *values)
  1438. def zremrangebylex(self, name, min, max):
  1439. """
  1440. Remove all elements in the sorted set ``name`` between the
  1441. lexicographical range specified by ``min`` and ``max``.
  1442. Returns the number of elements removed.
  1443. """
  1444. return self.execute_command('ZREMRANGEBYLEX', name, min, max)
  1445. def zremrangebyrank(self, name, min, max):
  1446. """
  1447. Remove all elements in the sorted set ``name`` with ranks between
  1448. ``min`` and ``max``. Values are 0-based, ordered from smallest score
  1449. to largest. Values can be negative indicating the highest scores.
  1450. Returns the number of elements removed
  1451. """
  1452. return self.execute_command('ZREMRANGEBYRANK', name, min, max)
  1453. def zremrangebyscore(self, name, min, max):
  1454. """
  1455. Remove all elements in the sorted set ``name`` with scores
  1456. between ``min`` and ``max``. Returns the number of elements removed.
  1457. """
  1458. return self.execute_command('ZREMRANGEBYSCORE', name, min, max)
  1459. def zrevrange(self, name, start, end, withscores=False,
  1460. score_cast_func=float):
  1461. """
  1462. Return a range of values from sorted set ``name`` between
  1463. ``start`` and ``end`` sorted in descending order.
  1464. ``start`` and ``end`` can be negative, indicating the end of the range.
  1465. ``withscores`` indicates to return the scores along with the values
  1466. The return type is a list of (value, score) pairs
  1467. ``score_cast_func`` a callable used to cast the score return value
  1468. """
  1469. pieces = ['ZREVRANGE', name, start, end]
  1470. if withscores:
  1471. pieces.append(Token('WITHSCORES'))
  1472. options = {
  1473. 'withscores': withscores,
  1474. 'score_cast_func': score_cast_func
  1475. }
  1476. return self.execute_command(*pieces, **options)
  1477. def zrevrangebyscore(self, name, max, min, start=None, num=None,
  1478. withscores=False, score_cast_func=float):
  1479. """
  1480. Return a range of values from the sorted set ``name`` with scores
  1481. between ``min`` and ``max`` in descending order.
  1482. If ``start`` and ``num`` are specified, then return a slice
  1483. of the range.
  1484. ``withscores`` indicates to return the scores along with the values.
  1485. The return type is a list of (value, score) pairs
  1486. ``score_cast_func`` a callable used to cast the score return value
  1487. """
  1488. if (start is not None and num is None) or \
  1489. (num is not None and start is None):
  1490. raise RedisError("``start`` and ``num`` must both be specified")
  1491. pieces = ['ZREVRANGEBYSCORE', name, max, min]
  1492. if start is not None and num is not None:
  1493. pieces.extend([Token('LIMIT'), start, num])
  1494. if withscores:
  1495. pieces.append(Token('WITHSCORES'))
  1496. options = {
  1497. 'withscores': withscores,
  1498. 'score_cast_func': score_cast_func
  1499. }
  1500. return self.execute_command(*pieces, **options)
  1501. def zrevrank(self, name, value):
  1502. """
  1503. Returns a 0-based value indicating the descending rank of
  1504. ``value`` in sorted set ``name``
  1505. """
  1506. return self.execute_command('ZREVRANK', name, value)
  1507. def zscore(self, name, value):
  1508. "Return the score of element ``value`` in sorted set ``name``"
  1509. return self.execute_command('ZSCORE', name, value)
  1510. def zunionstore(self, dest, keys, aggregate=None):
  1511. """
  1512. Union multiple sorted sets specified by ``keys`` into
  1513. a new sorted set, ``dest``. Scores in the destination will be
  1514. aggregated based on the ``aggregate``, or SUM if none is provided.
  1515. """
  1516. return self._zaggregate('ZUNIONSTORE', dest, keys, aggregate)
  1517. def _zaggregate(self, command, dest, keys, aggregate=None):
  1518. pieces = [command, dest, len(keys)]
  1519. if isinstance(keys, dict):
  1520. keys, weights = iterkeys(keys), itervalues(keys)
  1521. else:
  1522. weights = None
  1523. pieces.extend(keys)
  1524. if weights:
  1525. pieces.append(Token('WEIGHTS'))
  1526. pieces.extend(weights)
  1527. if aggregate:
  1528. pieces.append(Token('AGGREGATE'))
  1529. pieces.append(aggregate)
  1530. return self.execute_command(*pieces)
  1531. # HYPERLOGLOG COMMANDS
  1532. def pfadd(self, name, *values):
  1533. "Adds the specified elements to the specified HyperLogLog."
  1534. return self.execute_command('PFADD', name, *values)
  1535. def pfcount(self, *sources):
  1536. """
  1537. Return the approximated cardinality of
  1538. the set observed by the HyperLogLog at key(s).
  1539. """
  1540. return self.execute_command('PFCOUNT', *sources)
  1541. def pfmerge(self, dest, *sources):
  1542. "Merge N different HyperLogLogs into a single one."
  1543. return self.execute_command('PFMERGE', dest, *sources)
  1544. # HASH COMMANDS
  1545. def hdel(self, name, *keys):
  1546. "Delete ``keys`` from hash ``name``"
  1547. return self.execute_command('HDEL', name, *keys)
  1548. def hexists(self, name, key):
  1549. "Returns a boolean indicating if ``key`` exists within hash ``name``"
  1550. return self.execute_command('HEXISTS', name, key)
  1551. def hget(self, name, key):
  1552. "Return the value of ``key`` within the hash ``name``"
  1553. return self.execute_command('HGET', name, key)
  1554. def hgetall(self, name):
  1555. "Return a Python dict of the hash's name/value pairs"
  1556. return self.execute_command('HGETALL', name)
  1557. def hincrby(self, name, key, amount=1):
  1558. "Increment the value of ``key`` in hash ``name`` by ``amount``"
  1559. return self.execute_command('HINCRBY', name, key, amount)
  1560. def hincrbyfloat(self, name, key, amount=1.0):
  1561. """
  1562. Increment the value of ``key`` in hash ``name`` by floating ``amount``
  1563. """
  1564. return self.execute_command('HINCRBYFLOAT', name, key, amount)
  1565. def hkeys(self, name):
  1566. "Return the list of keys within hash ``name``"
  1567. return self.execute_command('HKEYS', name)
  1568. def hlen(self, name):
  1569. "Return the number of elements in hash ``name``"
  1570. return self.execute_command('HLEN', name)
  1571. def hset(self, name, key, value):
  1572. """
  1573. Set ``key`` to ``value`` within hash ``name``
  1574. Returns 1 if HSET created a new field, otherwise 0
  1575. """
  1576. return self.execute_command('HSET', name, key, value)
  1577. def hsetnx(self, name, key, value):
  1578. """
  1579. Set ``key`` to ``value`` within hash ``name`` if ``key`` does not
  1580. exist. Returns 1 if HSETNX created a field, otherwise 0.
  1581. """
  1582. return self.execute_command('HSETNX', name, key, value)
  1583. def hmset(self, name, mapping):
  1584. """
  1585. Set key to value within hash ``name`` for each corresponding
  1586. key and value from the ``mapping`` dict.
  1587. """
  1588. if not mapping:
  1589. raise DataError("'hmset' with 'mapping' of length 0")
  1590. items = []
  1591. for pair in iteritems(mapping):
  1592. items.extend(pair)
  1593. return self.execute_command('HMSET', name, *items)
  1594. def hmget(self, name, keys, *args):
  1595. "Returns a list of values ordered identically to ``keys``"
  1596. args = list_or_args(keys, args)
  1597. return self.execute_command('HMGET', name, *args)
  1598. def hvals(self, name):
  1599. "Return the list of values within hash ``name``"
  1600. return self.execute_command('HVALS', name)
  1601. def publish(self, channel, message):
  1602. """
  1603. Publish ``message`` on ``channel``.
  1604. Returns the number of subscribers the message was delivered to.
  1605. """
  1606. return self.execute_command('PUBLISH', channel, message)
  1607. def eval(self, script, numkeys, *keys_and_args):
  1608. """
  1609. Execute the Lua ``script``, specifying the ``numkeys`` the script
  1610. will touch and the key names and argument values in ``keys_and_args``.
  1611. Returns the result of the script.
  1612. In practice, use the object returned by ``register_script``. This
  1613. function exists purely for Redis API completion.
  1614. """
  1615. return self.execute_command('EVAL', script, numkeys, *keys_and_args)
  1616. def evalsha(self, sha, numkeys, *keys_and_args):
  1617. """
  1618. Use the ``sha`` to execute a Lua script already registered via EVAL
  1619. or SCRIPT LOAD. Specify the ``numkeys`` the script will touch and the
  1620. key names and argument values in ``keys_and_args``. Returns the result
  1621. of the script.
  1622. In practice, use the object returned by ``register_script``. This
  1623. function exists purely for Redis API completion.
  1624. """
  1625. return self.execute_command('EVALSHA', sha, numkeys, *keys_and_args)
  1626. def script_exists(self, *args):
  1627. """
  1628. Check if a script exists in the script cache by specifying the SHAs of
  1629. each script as ``args``. Returns a list of boolean values indicating if
  1630. if each already script exists in the cache.
  1631. """
  1632. return self.execute_command('SCRIPT EXISTS', *args)
  1633. def script_flush(self):
  1634. "Flush all scripts from the script cache"
  1635. return self.execute_command('SCRIPT FLUSH')
  1636. def script_kill(self):
  1637. "Kill the currently executing Lua script"
  1638. return self.execute_command('SCRIPT KILL')
  1639. def script_load(self, script):
  1640. "Load a Lua ``script`` into the script cache. Returns the SHA."
  1641. return self.execute_command('SCRIPT LOAD', script)
  1642. def register_script(self, script):
  1643. """
  1644. Register a Lua ``script`` specifying the ``keys`` it will touch.
  1645. Returns a Script object that is callable and hides the complexity of
  1646. deal with scripts, keys, and shas. This is the preferred way to work
  1647. with Lua scripts.
  1648. """
  1649. return Script(self, script)
  1650. class Redis(StrictRedis):
  1651. """
  1652. Provides backwards compatibility with older versions of redis-py that
  1653. changed arguments to some commands to be more Pythonic, sane, or by
  1654. accident.
  1655. """
  1656. # Overridden callbacks
  1657. RESPONSE_CALLBACKS = dict_merge(
  1658. StrictRedis.RESPONSE_CALLBACKS,
  1659. {
  1660. 'TTL': lambda r: r >= 0 and r or None,
  1661. 'PTTL': lambda r: r >= 0 and r or None,
  1662. }
  1663. )
  1664. def pipeline(self, transaction=True, shard_hint=None):
  1665. """
  1666. Return a new pipeline object that can queue multiple commands for
  1667. later execution. ``transaction`` indicates whether all commands
  1668. should be executed atomically. Apart from making a group of operations
  1669. atomic, pipelines are useful for reducing the back-and-forth overhead
  1670. between the client and server.
  1671. """
  1672. return Pipeline(
  1673. self.connection_pool,
  1674. self.response_callbacks,
  1675. transaction,
  1676. shard_hint)
  1677. def setex(self, name, value, time):
  1678. """
  1679. Set the value of key ``name`` to ``value`` that expires in ``time``
  1680. seconds. ``time`` can be represented by an integer or a Python
  1681. timedelta object.
  1682. """
  1683. if isinstance(time, datetime.timedelta):
  1684. time = time.seconds + time.days * 24 * 3600
  1685. return self.execute_command('SETEX', name, time, value)
  1686. def lrem(self, name, value, num=0):
  1687. """
  1688. Remove the first ``num`` occurrences of elements equal to ``value``
  1689. from the list stored at ``name``.
  1690. The ``num`` argument influences the operation in the following ways:
  1691. num > 0: Remove elements equal to value moving from head to tail.
  1692. num < 0: Remove elements equal to value moving from tail to head.
  1693. num = 0: Remove all elements equal to value.
  1694. """
  1695. return self.execute_command('LREM', name, num, value)
  1696. def zadd(self, name, *args, **kwargs):
  1697. """
  1698. NOTE: The order of arguments differs from that of the official ZADD
  1699. command. For backwards compatability, this method accepts arguments
  1700. in the form of name1, score1, name2, score2, while the official Redis
  1701. documents expects score1, name1, score2, name2.
  1702. If you're looking to use the standard syntax, consider using the
  1703. StrictRedis class. See the API Reference section of the docs for more
  1704. information.
  1705. Set any number of element-name, score pairs to the key ``name``. Pairs
  1706. can be specified in two ways:
  1707. As *args, in the form of: name1, score1, name2, score2, ...
  1708. or as **kwargs, in the form of: name1=score1, name2=score2, ...
  1709. The following example would add four values to the 'my-key' key:
  1710. redis.zadd('my-key', 'name1', 1.1, 'name2', 2.2, name3=3.3, name4=4.4)
  1711. """
  1712. pieces = []
  1713. if args:
  1714. if len(args) % 2 != 0:
  1715. raise RedisError("ZADD requires an equal number of "
  1716. "values and scores")
  1717. pieces.extend(reversed(args))
  1718. for pair in iteritems(kwargs):
  1719. pieces.append(pair[1])
  1720. pieces.append(pair[0])
  1721. return self.execute_command('ZADD', name, *pieces)
  1722. class PubSub(object):
  1723. """
  1724. PubSub provides publish, subscribe and listen support to Redis channels.
  1725. After subscribing to one or more channels, the listen() method will block
  1726. until a message arrives on one of the subscribed channels. That message
  1727. will be returned and it's safe to start listening again.
  1728. """
  1729. PUBLISH_MESSAGE_TYPES = ('message', 'pmessage')
  1730. UNSUBSCRIBE_MESSAGE_TYPES = ('unsubscribe', 'punsubscribe')
  1731. def __init__(self, connection_pool, shard_hint=None,
  1732. ignore_subscribe_messages=False):
  1733. self.connection_pool = connection_pool
  1734. self.shard_hint = shard_hint
  1735. self.ignore_subscribe_messages = ignore_subscribe_messages
  1736. self.connection = None
  1737. # we need to know the encoding options for this connection in order
  1738. # to lookup channel and pattern names for callback handlers.
  1739. conn = connection_pool.get_connection('pubsub', shard_hint)
  1740. try:
  1741. self.encoding = conn.encoding
  1742. self.encoding_errors = conn.encoding_errors
  1743. self.decode_responses = conn.decode_responses
  1744. finally:
  1745. connection_pool.release(conn)
  1746. self.reset()
  1747. def __del__(self):
  1748. try:
  1749. # if this object went out of scope prior to shutting down
  1750. # subscriptions, close the connection manually before
  1751. # returning it to the connection pool
  1752. self.reset()
  1753. except Exception:
  1754. pass
  1755. def reset(self):
  1756. if self.connection:
  1757. self.connection.disconnect()
  1758. self.connection.clear_connect_callbacks()
  1759. self.connection_pool.release(self.connection)
  1760. self.connection = None
  1761. self.channels = {}
  1762. self.patterns = {}
  1763. def close(self):
  1764. self.reset()
  1765. def on_connect(self, connection):
  1766. "Re-subscribe to any channels and patterns previously subscribed to"
  1767. # NOTE: for python3, we can't pass bytestrings as keyword arguments
  1768. # so we need to decode channel/pattern names back to unicode strings
  1769. # before passing them to [p]subscribe.
  1770. if self.channels:
  1771. channels = {}
  1772. for k, v in iteritems(self.channels):
  1773. if not self.decode_responses:
  1774. k = k.decode(self.encoding, self.encoding_errors)
  1775. channels[k] = v
  1776. self.subscribe(**channels)
  1777. if self.patterns:
  1778. patterns = {}
  1779. for k, v in iteritems(self.patterns):
  1780. if not self.decode_responses:
  1781. k = k.decode(self.encoding, self.encoding_errors)
  1782. patterns[k] = v
  1783. self.psubscribe(**patterns)
  1784. def encode(self, value):
  1785. """
  1786. Encode the value so that it's identical to what we'll
  1787. read off the connection
  1788. """
  1789. if self.decode_responses and isinstance(value, bytes):
  1790. value = value.decode(self.encoding, self.encoding_errors)
  1791. elif not self.decode_responses and isinstance(value, unicode):
  1792. value = value.encode(self.encoding, self.encoding_errors)
  1793. return value
  1794. @property
  1795. def subscribed(self):
  1796. "Indicates if there are subscriptions to any channels or patterns"
  1797. return bool(self.channels or self.patterns)
  1798. def execute_command(self, *args, **kwargs):
  1799. "Execute a publish/subscribe command"
  1800. # NOTE: don't parse the response in this function. it could pull a
  1801. # legitmate message off the stack if the connection is already
  1802. # subscribed to one or more channels
  1803. if self.connection is None:
  1804. self.connection = self.connection_pool.get_connection(
  1805. 'pubsub',
  1806. self.shard_hint
  1807. )
  1808. # register a callback that re-subscribes to any channels we
  1809. # were listening to when we were disconnected
  1810. self.connection.register_connect_callback(self.on_connect)
  1811. connection = self.connection
  1812. self._execute(connection, connection.send_command, *args)
  1813. def _execute(self, connection, command, *args):
  1814. try:
  1815. return command(*args)
  1816. except (ConnectionError, TimeoutError) as e:
  1817. connection.disconnect()
  1818. if not connection.retry_on_timeout and isinstance(e, TimeoutError):
  1819. raise
  1820. # Connect manually here. If the Redis server is down, this will
  1821. # fail and raise a ConnectionError as desired.
  1822. connection.connect()
  1823. # the ``on_connect`` callback should haven been called by the
  1824. # connection to resubscribe us to any channels and patterns we were
  1825. # previously listening to
  1826. return command(*args)
  1827. def parse_response(self, block=True, timeout=0):
  1828. "Parse the response from a publish/subscribe command"
  1829. connection = self.connection
  1830. if not block and not connection.can_read(timeout=timeout):
  1831. return None
  1832. return self._execute(connection, connection.read_response)
  1833. def psubscribe(self, *args, **kwargs):
  1834. """
  1835. Subscribe to channel patterns. Patterns supplied as keyword arguments
  1836. expect a pattern name as the key and a callable as the value. A
  1837. pattern's callable will be invoked automatically when a message is
  1838. received on that pattern rather than producing a message via
  1839. ``listen()``.
  1840. """
  1841. if args:
  1842. args = list_or_args(args[0], args[1:])
  1843. new_patterns = {}
  1844. new_patterns.update(dict.fromkeys(imap(self.encode, args)))
  1845. for pattern, handler in iteritems(kwargs):
  1846. new_patterns[self.encode(pattern)] = handler
  1847. ret_val = self.execute_command('PSUBSCRIBE', *iterkeys(new_patterns))
  1848. # update the patterns dict AFTER we send the command. we don't want to
  1849. # subscribe twice to these patterns, once for the command and again
  1850. # for the reconnection.
  1851. self.patterns.update(new_patterns)
  1852. return ret_val
  1853. def punsubscribe(self, *args):
  1854. """
  1855. Unsubscribe from the supplied patterns. If empy, unsubscribe from
  1856. all patterns.
  1857. """
  1858. if args:
  1859. args = list_or_args(args[0], args[1:])
  1860. return self.execute_command('PUNSUBSCRIBE', *args)
  1861. def subscribe(self, *args, **kwargs):
  1862. """
  1863. Subscribe to channels. Channels supplied as keyword arguments expect
  1864. a channel name as the key and a callable as the value. A channel's
  1865. callable will be invoked automatically when a message is received on
  1866. that channel rather than producing a message via ``listen()`` or
  1867. ``get_message()``.
  1868. """
  1869. if args:
  1870. args = list_or_args(args[0], args[1:])
  1871. new_channels = {}
  1872. new_channels.update(dict.fromkeys(imap(self.encode, args)))
  1873. for channel, handler in iteritems(kwargs):
  1874. new_channels[self.encode(channel)] = handler
  1875. ret_val = self.execute_command('SUBSCRIBE', *iterkeys(new_channels))
  1876. # update the channels dict AFTER we send the command. we don't want to
  1877. # subscribe twice to these channels, once for the command and again
  1878. # for the reconnection.
  1879. self.channels.update(new_channels)
  1880. return ret_val
  1881. def unsubscribe(self, *args):
  1882. """
  1883. Unsubscribe from the supplied channels. If empty, unsubscribe from
  1884. all channels
  1885. """
  1886. if args:
  1887. args = list_or_args(args[0], args[1:])
  1888. return self.execute_command('UNSUBSCRIBE', *args)
  1889. def listen(self):
  1890. "Listen for messages on channels this client has been subscribed to"
  1891. while self.subscribed:
  1892. response = self.handle_message(self.parse_response(block=True))
  1893. if response is not None:
  1894. yield response
  1895. def get_message(self, ignore_subscribe_messages=False, timeout=0):
  1896. """
  1897. Get the next message if one is available, otherwise None.
  1898. If timeout is specified, the system will wait for `timeout` seconds
  1899. before returning. Timeout should be specified as a floating point
  1900. number.
  1901. """
  1902. response = self.parse_response(block=False, timeout=timeout)
  1903. if response:
  1904. return self.handle_message(response, ignore_subscribe_messages)
  1905. return None
  1906. def handle_message(self, response, ignore_subscribe_messages=False):
  1907. """
  1908. Parses a pub/sub message. If the channel or pattern was subscribed to
  1909. with a message handler, the handler is invoked instead of a parsed
  1910. message being returned.
  1911. """
  1912. message_type = nativestr(response[0])
  1913. if message_type == 'pmessage':
  1914. message = {
  1915. 'type': message_type,
  1916. 'pattern': response[1],
  1917. 'channel': response[2],
  1918. 'data': response[3]
  1919. }
  1920. else:
  1921. message = {
  1922. 'type': message_type,
  1923. 'pattern': None,
  1924. 'channel': response[1],
  1925. 'data': response[2]
  1926. }
  1927. # if this is an unsubscribe message, remove it from memory
  1928. if message_type in self.UNSUBSCRIBE_MESSAGE_TYPES:
  1929. subscribed_dict = None
  1930. if message_type == 'punsubscribe':
  1931. subscribed_dict = self.patterns
  1932. else:
  1933. subscribed_dict = self.channels
  1934. try:
  1935. del subscribed_dict[message['channel']]
  1936. except KeyError:
  1937. pass
  1938. if message_type in self.PUBLISH_MESSAGE_TYPES:
  1939. # if there's a message handler, invoke it
  1940. handler = None
  1941. if message_type == 'pmessage':
  1942. handler = self.patterns.get(message['pattern'], None)
  1943. else:
  1944. handler = self.channels.get(message['channel'], None)
  1945. if handler:
  1946. handler(message)
  1947. return None
  1948. else:
  1949. # this is a subscribe/unsubscribe message. ignore if we don't
  1950. # want them
  1951. if ignore_subscribe_messages or self.ignore_subscribe_messages:
  1952. return None
  1953. return message
  1954. def run_in_thread(self, sleep_time=0):
  1955. for channel, handler in iteritems(self.channels):
  1956. if handler is None:
  1957. raise PubSubError("Channel: '%s' has no handler registered")
  1958. for pattern, handler in iteritems(self.patterns):
  1959. if handler is None:
  1960. raise PubSubError("Pattern: '%s' has no handler registered")
  1961. thread = PubSubWorkerThread(self, sleep_time)
  1962. thread.start()
  1963. return thread
  1964. class PubSubWorkerThread(threading.Thread):
  1965. def __init__(self, pubsub, sleep_time):
  1966. super(PubSubWorkerThread, self).__init__()
  1967. self.pubsub = pubsub
  1968. self.sleep_time = sleep_time
  1969. self._running = False
  1970. def run(self):
  1971. if self._running:
  1972. return
  1973. self._running = True
  1974. pubsub = self.pubsub
  1975. sleep_time = self.sleep_time
  1976. while pubsub.subscribed:
  1977. pubsub.get_message(ignore_subscribe_messages=True,
  1978. timeout=sleep_time)
  1979. pubsub.close()
  1980. self._running = False
  1981. def stop(self):
  1982. # stopping simply unsubscribes from all channels and patterns.
  1983. # the unsubscribe responses that are generated will short circuit
  1984. # the loop in run(), calling pubsub.close() to clean up the connection
  1985. self.pubsub.unsubscribe()
  1986. self.pubsub.punsubscribe()
  1987. class BasePipeline(object):
  1988. """
  1989. Pipelines provide a way to transmit multiple commands to the Redis server
  1990. in one transmission. This is convenient for batch processing, such as
  1991. saving all the values in a list to Redis.
  1992. All commands executed within a pipeline are wrapped with MULTI and EXEC
  1993. calls. This guarantees all commands executed in the pipeline will be
  1994. executed atomically.
  1995. Any command raising an exception does *not* halt the execution of
  1996. subsequent commands in the pipeline. Instead, the exception is caught
  1997. and its instance is placed into the response list returned by execute().
  1998. Code iterating over the response list should be able to deal with an
  1999. instance of an exception as a potential value. In general, these will be
  2000. ResponseError exceptions, such as those raised when issuing a command
  2001. on a key of a different datatype.
  2002. """
  2003. UNWATCH_COMMANDS = set(('DISCARD', 'EXEC', 'UNWATCH'))
  2004. def __init__(self, connection_pool, response_callbacks, transaction,
  2005. shard_hint):
  2006. self.connection_pool = connection_pool
  2007. self.connection = None
  2008. self.response_callbacks = response_callbacks
  2009. self.transaction = transaction
  2010. self.shard_hint = shard_hint
  2011. self.watching = False
  2012. self.reset()
  2013. def __enter__(self):
  2014. return self
  2015. def __exit__(self, exc_type, exc_value, traceback):
  2016. self.reset()
  2017. def __del__(self):
  2018. try:
  2019. self.reset()
  2020. except Exception:
  2021. pass
  2022. def __len__(self):
  2023. return len(self.command_stack)
  2024. def reset(self):
  2025. self.command_stack = []
  2026. self.scripts = set()
  2027. # make sure to reset the connection state in the event that we were
  2028. # watching something
  2029. if self.watching and self.connection:
  2030. try:
  2031. # call this manually since our unwatch or
  2032. # immediate_execute_command methods can call reset()
  2033. self.connection.send_command('UNWATCH')
  2034. self.connection.read_response()
  2035. except ConnectionError:
  2036. # disconnect will also remove any previous WATCHes
  2037. self.connection.disconnect()
  2038. # clean up the other instance attributes
  2039. self.watching = False
  2040. self.explicit_transaction = False
  2041. # we can safely return the connection to the pool here since we're
  2042. # sure we're no longer WATCHing anything
  2043. if self.connection:
  2044. self.connection_pool.release(self.connection)
  2045. self.connection = None
  2046. def multi(self):
  2047. """
  2048. Start a transactional block of the pipeline after WATCH commands
  2049. are issued. End the transactional block with `execute`.
  2050. """
  2051. if self.explicit_transaction:
  2052. raise RedisError('Cannot issue nested calls to MULTI')
  2053. if self.command_stack:
  2054. raise RedisError('Commands without an initial WATCH have already '
  2055. 'been issued')
  2056. self.explicit_transaction = True
  2057. def execute_command(self, *args, **kwargs):
  2058. if (self.watching or args[0] == 'WATCH') and \
  2059. not self.explicit_transaction:
  2060. return self.immediate_execute_command(*args, **kwargs)
  2061. return self.pipeline_execute_command(*args, **kwargs)
  2062. def immediate_execute_command(self, *args, **options):
  2063. """
  2064. Execute a command immediately, but don't auto-retry on a
  2065. ConnectionError if we're already WATCHing a variable. Used when
  2066. issuing WATCH or subsequent commands retrieving their values but before
  2067. MULTI is called.
  2068. """
  2069. command_name = args[0]
  2070. conn = self.connection
  2071. # if this is the first call, we need a connection
  2072. if not conn:
  2073. conn = self.connection_pool.get_connection(command_name,
  2074. self.shard_hint)
  2075. self.connection = conn
  2076. try:
  2077. conn.send_command(*args)
  2078. return self.parse_response(conn, command_name, **options)
  2079. except (ConnectionError, TimeoutError) as e:
  2080. conn.disconnect()
  2081. if not conn.retry_on_timeout and isinstance(e, TimeoutError):
  2082. raise
  2083. # if we're not already watching, we can safely retry the command
  2084. try:
  2085. if not self.watching:
  2086. conn.send_command(*args)
  2087. return self.parse_response(conn, command_name, **options)
  2088. except ConnectionError:
  2089. # the retry failed so cleanup.
  2090. conn.disconnect()
  2091. self.reset()
  2092. raise
  2093. def pipeline_execute_command(self, *args, **options):
  2094. """
  2095. Stage a command to be executed when execute() is next called
  2096. Returns the current Pipeline object back so commands can be
  2097. chained together, such as:
  2098. pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
  2099. At some other point, you can then run: pipe.execute(),
  2100. which will execute all commands queued in the pipe.
  2101. """
  2102. self.command_stack.append((args, options))
  2103. return self
  2104. def _execute_transaction(self, connection, commands, raise_on_error):
  2105. cmds = chain([(('MULTI', ), {})], commands, [(('EXEC', ), {})])
  2106. all_cmds = connection.pack_commands([args for args, _ in cmds])
  2107. connection.send_packed_command(all_cmds)
  2108. errors = []
  2109. # parse off the response for MULTI
  2110. # NOTE: we need to handle ResponseErrors here and continue
  2111. # so that we read all the additional command messages from
  2112. # the socket
  2113. try:
  2114. self.parse_response(connection, '_')
  2115. except ResponseError:
  2116. errors.append((0, sys.exc_info()[1]))
  2117. # and all the other commands
  2118. for i, command in enumerate(commands):
  2119. try:
  2120. self.parse_response(connection, '_')
  2121. except ResponseError:
  2122. ex = sys.exc_info()[1]
  2123. self.annotate_exception(ex, i + 1, command[0])
  2124. errors.append((i, ex))
  2125. # parse the EXEC.
  2126. try:
  2127. response = self.parse_response(connection, '_')
  2128. except ExecAbortError:
  2129. if self.explicit_transaction:
  2130. self.immediate_execute_command('DISCARD')
  2131. if errors:
  2132. raise errors[0][1]
  2133. raise sys.exc_info()[1]
  2134. if response is None:
  2135. raise WatchError("Watched variable changed.")
  2136. # put any parse errors into the response
  2137. for i, e in errors:
  2138. response.insert(i, e)
  2139. if len(response) != len(commands):
  2140. self.connection.disconnect()
  2141. raise ResponseError("Wrong number of response items from "
  2142. "pipeline execution")
  2143. # find any errors in the response and raise if necessary
  2144. if raise_on_error:
  2145. self.raise_first_error(commands, response)
  2146. # We have to run response callbacks manually
  2147. data = []
  2148. for r, cmd in izip(response, commands):
  2149. if not isinstance(r, Exception):
  2150. args, options = cmd
  2151. command_name = args[0]
  2152. if command_name in self.response_callbacks:
  2153. r = self.response_callbacks[command_name](r, **options)
  2154. data.append(r)
  2155. return data
  2156. def _execute_pipeline(self, connection, commands, raise_on_error):
  2157. # build up all commands into a single request to increase network perf
  2158. all_cmds = connection.pack_commands([args for args, _ in commands])
  2159. connection.send_packed_command(all_cmds)
  2160. response = []
  2161. for args, options in commands:
  2162. try:
  2163. response.append(
  2164. self.parse_response(connection, args[0], **options))
  2165. except ResponseError:
  2166. response.append(sys.exc_info()[1])
  2167. if raise_on_error:
  2168. self.raise_first_error(commands, response)
  2169. return response
  2170. def raise_first_error(self, commands, response):
  2171. for i, r in enumerate(response):
  2172. if isinstance(r, ResponseError):
  2173. self.annotate_exception(r, i + 1, commands[i][0])
  2174. raise r
  2175. def annotate_exception(self, exception, number, command):
  2176. cmd = safe_unicode(' ').join(imap(safe_unicode, command))
  2177. msg = unicode('Command # %d (%s) of pipeline caused error: %s') % (
  2178. number, cmd, safe_unicode(exception.args[0]))
  2179. exception.args = (msg,) + exception.args[1:]
  2180. def parse_response(self, connection, command_name, **options):
  2181. result = StrictRedis.parse_response(
  2182. self, connection, command_name, **options)
  2183. if command_name in self.UNWATCH_COMMANDS:
  2184. self.watching = False
  2185. elif command_name == 'WATCH':
  2186. self.watching = True
  2187. return result
  2188. def load_scripts(self):
  2189. # make sure all scripts that are about to be run on this pipeline exist
  2190. scripts = list(self.scripts)
  2191. immediate = self.immediate_execute_command
  2192. shas = [s.sha for s in scripts]
  2193. # we can't use the normal script_* methods because they would just
  2194. # get buffered in the pipeline.
  2195. exists = immediate('SCRIPT', 'EXISTS', *shas, **{'parse': 'EXISTS'})
  2196. if not all(exists):
  2197. for s, exist in izip(scripts, exists):
  2198. if not exist:
  2199. s.sha = immediate('SCRIPT', 'LOAD', s.script,
  2200. **{'parse': 'LOAD'})
  2201. def execute(self, raise_on_error=True):
  2202. "Execute all the commands in the current pipeline"
  2203. stack = self.command_stack
  2204. if not stack:
  2205. return []
  2206. if self.scripts:
  2207. self.load_scripts()
  2208. if self.transaction or self.explicit_transaction:
  2209. execute = self._execute_transaction
  2210. else:
  2211. execute = self._execute_pipeline
  2212. conn = self.connection
  2213. if not conn:
  2214. conn = self.connection_pool.get_connection('MULTI',
  2215. self.shard_hint)
  2216. # assign to self.connection so reset() releases the connection
  2217. # back to the pool after we're done
  2218. self.connection = conn
  2219. try:
  2220. return execute(conn, stack, raise_on_error)
  2221. except (ConnectionError, TimeoutError) as e:
  2222. conn.disconnect()
  2223. if not conn.retry_on_timeout and isinstance(e, TimeoutError):
  2224. raise
  2225. # if we were watching a variable, the watch is no longer valid
  2226. # since this connection has died. raise a WatchError, which
  2227. # indicates the user should retry his transaction. If this is more
  2228. # than a temporary failure, the WATCH that the user next issues
  2229. # will fail, propegating the real ConnectionError
  2230. if self.watching:
  2231. raise WatchError("A ConnectionError occured on while watching "
  2232. "one or more keys")
  2233. # otherwise, it's safe to retry since the transaction isn't
  2234. # predicated on any state
  2235. return execute(conn, stack, raise_on_error)
  2236. finally:
  2237. self.reset()
  2238. def watch(self, *names):
  2239. "Watches the values at keys ``names``"
  2240. if self.explicit_transaction:
  2241. raise RedisError('Cannot issue a WATCH after a MULTI')
  2242. return self.execute_command('WATCH', *names)
  2243. def unwatch(self):
  2244. "Unwatches all previously specified keys"
  2245. return self.watching and self.execute_command('UNWATCH') or True
  2246. def script_load_for_pipeline(self, script):
  2247. "Make sure scripts are loaded prior to pipeline execution"
  2248. # we need the sha now so that Script.__call__ can use it to run
  2249. # evalsha.
  2250. if not script.sha:
  2251. script.sha = self.immediate_execute_command('SCRIPT', 'LOAD',
  2252. script.script,
  2253. **{'parse': 'LOAD'})
  2254. self.scripts.add(script)
  2255. class StrictPipeline(BasePipeline, StrictRedis):
  2256. "Pipeline for the StrictRedis class"
  2257. pass
  2258. class Pipeline(BasePipeline, Redis):
  2259. "Pipeline for the Redis class"
  2260. pass
  2261. class Script(object):
  2262. "An executable Lua script object returned by ``register_script``"
  2263. def __init__(self, registered_client, script):
  2264. self.registered_client = registered_client
  2265. self.script = script
  2266. self.sha = ''
  2267. def __call__(self, keys=[], args=[], client=None):
  2268. "Execute the script, passing any required ``args``"
  2269. if client is None:
  2270. client = self.registered_client
  2271. args = tuple(keys) + tuple(args)
  2272. # make sure the Redis server knows about the script
  2273. if isinstance(client, BasePipeline):
  2274. # make sure this script is good to go on pipeline
  2275. client.script_load_for_pipeline(self)
  2276. try:
  2277. return client.evalsha(self.sha, len(keys), *args)
  2278. except NoScriptError:
  2279. # Maybe the client is pointed to a differnet server than the client
  2280. # that created this instance?
  2281. self.sha = client.script_load(self.script)
  2282. return client.evalsha(self.sha, len(keys), *args)