You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

3849 rivejä
143 KiB

  1. from __future__ import unicode_literals
  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. import re
  10. import hashlib
  11. from redis._compat import (basestring, imap, iteritems, iterkeys,
  12. itervalues, izip, long, nativestr, safe_unicode)
  13. from redis.connection import (ConnectionPool, UnixDomainSocketConnection,
  14. SSLConnection)
  15. from redis.lock import Lock
  16. from redis.exceptions import (
  17. ConnectionError,
  18. DataError,
  19. ExecAbortError,
  20. NoScriptError,
  21. PubSubError,
  22. RedisError,
  23. ResponseError,
  24. TimeoutError,
  25. WatchError,
  26. )
  27. SYM_EMPTY = b''
  28. EMPTY_RESPONSE = 'EMPTY_RESPONSE'
  29. def list_or_args(keys, args):
  30. # returns a single new list combining keys and args
  31. try:
  32. iter(keys)
  33. # a string or bytes instance can be iterated, but indicates
  34. # keys wasn't passed as a list
  35. if isinstance(keys, (basestring, bytes)):
  36. keys = [keys]
  37. else:
  38. keys = list(keys)
  39. except TypeError:
  40. keys = [keys]
  41. if args:
  42. keys.extend(args)
  43. return keys
  44. def timestamp_to_datetime(response):
  45. "Converts a unix timestamp to a Python datetime object"
  46. if not response:
  47. return None
  48. try:
  49. response = int(response)
  50. except ValueError:
  51. return None
  52. return datetime.datetime.fromtimestamp(response)
  53. def string_keys_to_dict(key_string, callback):
  54. return dict.fromkeys(key_string.split(), callback)
  55. def dict_merge(*dicts):
  56. merged = {}
  57. for d in dicts:
  58. merged.update(d)
  59. return merged
  60. class CaseInsensitiveDict(dict):
  61. "Case insensitive dict implementation. Assumes string keys only."
  62. def __init__(self, data):
  63. for k, v in iteritems(data):
  64. self[k.upper()] = v
  65. def __contains__(self, k):
  66. return super(CaseInsensitiveDict, self).__contains__(k.upper())
  67. def __delitem__(self, k):
  68. super(CaseInsensitiveDict, self).__delitem__(k.upper())
  69. def __getitem__(self, k):
  70. return super(CaseInsensitiveDict, self).__getitem__(k.upper())
  71. def get(self, k, default=None):
  72. return super(CaseInsensitiveDict, self).get(k.upper(), default)
  73. def __setitem__(self, k, v):
  74. super(CaseInsensitiveDict, self).__setitem__(k.upper(), v)
  75. def update(self, data):
  76. data = CaseInsensitiveDict(data)
  77. super(CaseInsensitiveDict, self).update(data)
  78. def parse_debug_object(response):
  79. "Parse the results of Redis's DEBUG OBJECT command into a Python dict"
  80. # The 'type' of the object is the first item in the response, but isn't
  81. # prefixed with a name
  82. response = nativestr(response)
  83. response = 'type:' + response
  84. response = dict(kv.split(':') for kv in response.split())
  85. # parse some expected int values from the string response
  86. # note: this cmd isn't spec'd so these may not appear in all redis versions
  87. int_fields = ('refcount', 'serializedlength', 'lru', 'lru_seconds_idle')
  88. for field in int_fields:
  89. if field in response:
  90. response[field] = int(response[field])
  91. return response
  92. def parse_object(response, infotype):
  93. "Parse the results of an OBJECT command"
  94. if infotype in ('idletime', 'refcount'):
  95. return int_or_none(response)
  96. return response
  97. def parse_info(response):
  98. "Parse the result of Redis's INFO command into a Python dict"
  99. info = {}
  100. response = nativestr(response)
  101. def get_value(value):
  102. if ',' not in value or '=' not in value:
  103. try:
  104. if '.' in value:
  105. return float(value)
  106. else:
  107. return int(value)
  108. except ValueError:
  109. return value
  110. else:
  111. sub_dict = {}
  112. for item in value.split(','):
  113. k, v = item.rsplit('=', 1)
  114. sub_dict[k] = get_value(v)
  115. return sub_dict
  116. for line in response.splitlines():
  117. if line and not line.startswith('#'):
  118. if line.find(':') != -1:
  119. # Split, the info fields keys and values.
  120. # Note that the value may contain ':'. but the 'host:'
  121. # pseudo-command is the only case where the key contains ':'
  122. key, value = line.split(':', 1)
  123. if key == 'cmdstat_host':
  124. key, value = line.rsplit(':', 1)
  125. info[key] = get_value(value)
  126. else:
  127. # if the line isn't splittable, append it to the "__raw__" key
  128. info.setdefault('__raw__', []).append(line)
  129. return info
  130. SENTINEL_STATE_TYPES = {
  131. 'can-failover-its-master': int,
  132. 'config-epoch': int,
  133. 'down-after-milliseconds': int,
  134. 'failover-timeout': int,
  135. 'info-refresh': int,
  136. 'last-hello-message': int,
  137. 'last-ok-ping-reply': int,
  138. 'last-ping-reply': int,
  139. 'last-ping-sent': int,
  140. 'master-link-down-time': int,
  141. 'master-port': int,
  142. 'num-other-sentinels': int,
  143. 'num-slaves': int,
  144. 'o-down-time': int,
  145. 'pending-commands': int,
  146. 'parallel-syncs': int,
  147. 'port': int,
  148. 'quorum': int,
  149. 'role-reported-time': int,
  150. 's-down-time': int,
  151. 'slave-priority': int,
  152. 'slave-repl-offset': int,
  153. 'voted-leader-epoch': int
  154. }
  155. def parse_sentinel_state(item):
  156. result = pairs_to_dict_typed(item, SENTINEL_STATE_TYPES)
  157. flags = set(result['flags'].split(','))
  158. for name, flag in (('is_master', 'master'), ('is_slave', 'slave'),
  159. ('is_sdown', 's_down'), ('is_odown', 'o_down'),
  160. ('is_sentinel', 'sentinel'),
  161. ('is_disconnected', 'disconnected'),
  162. ('is_master_down', 'master_down')):
  163. result[name] = flag in flags
  164. return result
  165. def parse_sentinel_master(response):
  166. return parse_sentinel_state(imap(nativestr, response))
  167. def parse_sentinel_masters(response):
  168. result = {}
  169. for item in response:
  170. state = parse_sentinel_state(imap(nativestr, item))
  171. result[state['name']] = state
  172. return result
  173. def parse_sentinel_slaves_and_sentinels(response):
  174. return [parse_sentinel_state(imap(nativestr, item)) for item in response]
  175. def parse_sentinel_get_master(response):
  176. return response and (response[0], int(response[1])) or None
  177. def pairs_to_dict(response, decode_keys=False):
  178. "Create a dict given a list of key/value pairs"
  179. if response is None:
  180. return {}
  181. if decode_keys:
  182. # the iter form is faster, but I don't know how to make that work
  183. # with a nativestr() map
  184. return dict(izip(imap(nativestr, response[::2]), response[1::2]))
  185. else:
  186. it = iter(response)
  187. return dict(izip(it, it))
  188. def pairs_to_dict_typed(response, type_info):
  189. it = iter(response)
  190. result = {}
  191. for key, value in izip(it, it):
  192. if key in type_info:
  193. try:
  194. value = type_info[key](value)
  195. except Exception:
  196. # if for some reason the value can't be coerced, just use
  197. # the string value
  198. pass
  199. result[key] = value
  200. return result
  201. def zset_score_pairs(response, **options):
  202. """
  203. If ``withscores`` is specified in the options, return the response as
  204. a list of (value, score) pairs
  205. """
  206. if not response or not options.get('withscores'):
  207. return response
  208. score_cast_func = options.get('score_cast_func', float)
  209. it = iter(response)
  210. return list(izip(it, imap(score_cast_func, it)))
  211. def sort_return_tuples(response, **options):
  212. """
  213. If ``groups`` is specified, return the response as a list of
  214. n-element tuples with n being the value found in options['groups']
  215. """
  216. if not response or not options.get('groups'):
  217. return response
  218. n = options['groups']
  219. return list(izip(*[response[i::n] for i in range(n)]))
  220. def int_or_none(response):
  221. if response is None:
  222. return None
  223. return int(response)
  224. def nativestr_or_none(response):
  225. if response is None:
  226. return None
  227. return nativestr(response)
  228. def parse_stream_list(response):
  229. if response is None:
  230. return None
  231. data = []
  232. for r in response:
  233. if r is not None:
  234. data.append((r[0], pairs_to_dict(r[1])))
  235. else:
  236. data.append((None, None))
  237. return data
  238. def pairs_to_dict_with_nativestr_keys(response):
  239. return pairs_to_dict(response, decode_keys=True)
  240. def parse_list_of_dicts(response):
  241. return list(imap(pairs_to_dict_with_nativestr_keys, response))
  242. def parse_xclaim(response, **options):
  243. if options.get('parse_justid', False):
  244. return response
  245. return parse_stream_list(response)
  246. def parse_xinfo_stream(response):
  247. data = pairs_to_dict(response, decode_keys=True)
  248. first = data['first-entry']
  249. if first is not None:
  250. data['first-entry'] = (first[0], pairs_to_dict(first[1]))
  251. last = data['last-entry']
  252. if last is not None:
  253. data['last-entry'] = (last[0], pairs_to_dict(last[1]))
  254. return data
  255. def parse_xread(response):
  256. if response is None:
  257. return []
  258. return [[r[0], parse_stream_list(r[1])] for r in response]
  259. def parse_xpending(response, **options):
  260. if options.get('parse_detail', False):
  261. return parse_xpending_range(response)
  262. consumers = [{'name': n, 'pending': long(p)} for n, p in response[3] or []]
  263. return {
  264. 'pending': response[0],
  265. 'min': response[1],
  266. 'max': response[2],
  267. 'consumers': consumers
  268. }
  269. def parse_xpending_range(response):
  270. k = ('message_id', 'consumer', 'time_since_delivered', 'times_delivered')
  271. return [dict(izip(k, r)) for r in response]
  272. def float_or_none(response):
  273. if response is None:
  274. return None
  275. return float(response)
  276. def bool_ok(response):
  277. return nativestr(response) == 'OK'
  278. def parse_zadd(response, **options):
  279. if response is None:
  280. return None
  281. if options.get('as_score'):
  282. return float(response)
  283. return int(response)
  284. def parse_client_list(response, **options):
  285. clients = []
  286. for c in nativestr(response).splitlines():
  287. # Values might contain '='
  288. clients.append(dict(pair.split('=', 1) for pair in c.split(' ')))
  289. return clients
  290. def parse_config_get(response, **options):
  291. response = [nativestr(i) if i is not None else None for i in response]
  292. return response and pairs_to_dict(response) or {}
  293. def parse_scan(response, **options):
  294. cursor, r = response
  295. return long(cursor), r
  296. def parse_hscan(response, **options):
  297. cursor, r = response
  298. return long(cursor), r and pairs_to_dict(r) or {}
  299. def parse_zscan(response, **options):
  300. score_cast_func = options.get('score_cast_func', float)
  301. cursor, r = response
  302. it = iter(r)
  303. return long(cursor), list(izip(it, imap(score_cast_func, it)))
  304. def parse_slowlog_get(response, **options):
  305. return [{
  306. 'id': item[0],
  307. 'start_time': int(item[1]),
  308. 'duration': int(item[2]),
  309. 'command': b' '.join(item[3])
  310. } for item in response]
  311. def parse_cluster_info(response, **options):
  312. response = nativestr(response)
  313. return dict(line.split(':') for line in response.splitlines() if line)
  314. def _parse_node_line(line):
  315. line_items = line.split(' ')
  316. node_id, addr, flags, master_id, ping, pong, epoch, \
  317. connected = line.split(' ')[:8]
  318. slots = [sl.split('-') for sl in line_items[8:]]
  319. node_dict = {
  320. 'node_id': node_id,
  321. 'flags': flags,
  322. 'master_id': master_id,
  323. 'last_ping_sent': ping,
  324. 'last_pong_rcvd': pong,
  325. 'epoch': epoch,
  326. 'slots': slots,
  327. 'connected': True if connected == 'connected' else False
  328. }
  329. return addr, node_dict
  330. def parse_cluster_nodes(response, **options):
  331. response = nativestr(response)
  332. raw_lines = response
  333. if isinstance(response, basestring):
  334. raw_lines = response.splitlines()
  335. return dict(_parse_node_line(line) for line in raw_lines)
  336. def parse_georadius_generic(response, **options):
  337. if options['store'] or options['store_dist']:
  338. # `store` and `store_diff` cant be combined
  339. # with other command arguments.
  340. return response
  341. if type(response) != list:
  342. response_list = [response]
  343. else:
  344. response_list = response
  345. if not options['withdist'] and not options['withcoord']\
  346. and not options['withhash']:
  347. # just a bunch of places
  348. return response_list
  349. cast = {
  350. 'withdist': float,
  351. 'withcoord': lambda ll: (float(ll[0]), float(ll[1])),
  352. 'withhash': int
  353. }
  354. # zip all output results with each casting functino to get
  355. # the properly native Python value.
  356. f = [lambda x: x]
  357. f += [cast[o] for o in ['withdist', 'withhash', 'withcoord'] if options[o]]
  358. return [
  359. list(map(lambda fv: fv[0](fv[1]), zip(f, r))) for r in response_list
  360. ]
  361. def parse_pubsub_numsub(response, **options):
  362. return list(zip(response[0::2], response[1::2]))
  363. def parse_client_kill(response, **options):
  364. if isinstance(response, (long, int)):
  365. return int(response)
  366. return nativestr(response) == 'OK'
  367. class Redis(object):
  368. """
  369. Implementation of the Redis protocol.
  370. This abstract class provides a Python interface to all Redis commands
  371. and an implementation of the Redis protocol.
  372. Connection and Pipeline derive from this, implementing how
  373. the commands are sent and received to the Redis server
  374. """
  375. RESPONSE_CALLBACKS = dict_merge(
  376. string_keys_to_dict(
  377. 'AUTH EXPIRE EXPIREAT HEXISTS HMSET MOVE MSETNX PERSIST '
  378. 'PSETEX RENAMENX SISMEMBER SMOVE SETEX SETNX',
  379. bool
  380. ),
  381. string_keys_to_dict(
  382. 'BITCOUNT BITPOS DECRBY DEL EXISTS GEOADD GETBIT HDEL HLEN '
  383. 'HSTRLEN INCRBY LINSERT LLEN LPUSHX PFADD PFCOUNT RPUSHX SADD '
  384. 'SCARD SDIFFSTORE SETBIT SETRANGE SINTERSTORE SREM STRLEN '
  385. 'SUNIONSTORE UNLINK XACK XDEL XLEN XTRIM ZCARD ZLEXCOUNT ZREM '
  386. 'ZREMRANGEBYLEX ZREMRANGEBYRANK ZREMRANGEBYSCORE',
  387. int
  388. ),
  389. string_keys_to_dict(
  390. 'INCRBYFLOAT HINCRBYFLOAT',
  391. float
  392. ),
  393. string_keys_to_dict(
  394. # these return OK, or int if redis-server is >=1.3.4
  395. 'LPUSH RPUSH',
  396. lambda r: isinstance(r, (long, int)) and r or nativestr(r) == 'OK'
  397. ),
  398. string_keys_to_dict('SORT', sort_return_tuples),
  399. string_keys_to_dict('ZSCORE ZINCRBY GEODIST', float_or_none),
  400. string_keys_to_dict(
  401. 'FLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE READONLY READWRITE '
  402. 'RENAME SAVE SELECT SHUTDOWN SLAVEOF SWAPDB WATCH UNWATCH ',
  403. bool_ok
  404. ),
  405. string_keys_to_dict('BLPOP BRPOP', lambda r: r and tuple(r) or None),
  406. string_keys_to_dict(
  407. 'SDIFF SINTER SMEMBERS SUNION',
  408. lambda r: r and set(r) or set()
  409. ),
  410. string_keys_to_dict(
  411. 'ZPOPMAX ZPOPMIN ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCORE',
  412. zset_score_pairs
  413. ),
  414. string_keys_to_dict('BZPOPMIN BZPOPMAX', \
  415. lambda r: r and (r[0], r[1], float(r[2])) or None),
  416. string_keys_to_dict('ZRANK ZREVRANK', int_or_none),
  417. string_keys_to_dict('XREVRANGE XRANGE', parse_stream_list),
  418. string_keys_to_dict('XREAD XREADGROUP', parse_xread),
  419. string_keys_to_dict('BGREWRITEAOF BGSAVE', lambda r: True),
  420. {
  421. 'CLIENT GETNAME': lambda r: r and nativestr(r),
  422. 'CLIENT ID': int,
  423. 'CLIENT KILL': parse_client_kill,
  424. 'CLIENT LIST': parse_client_list,
  425. 'CLIENT SETNAME': bool_ok,
  426. 'CLIENT UNBLOCK': lambda r: r and int(r) == 1 or False,
  427. 'CLIENT PAUSE': bool_ok,
  428. 'CLUSTER ADDSLOTS': bool_ok,
  429. 'CLUSTER COUNT-FAILURE-REPORTS': lambda x: int(x),
  430. 'CLUSTER COUNTKEYSINSLOT': lambda x: int(x),
  431. 'CLUSTER DELSLOTS': bool_ok,
  432. 'CLUSTER FAILOVER': bool_ok,
  433. 'CLUSTER FORGET': bool_ok,
  434. 'CLUSTER INFO': parse_cluster_info,
  435. 'CLUSTER KEYSLOT': lambda x: int(x),
  436. 'CLUSTER MEET': bool_ok,
  437. 'CLUSTER NODES': parse_cluster_nodes,
  438. 'CLUSTER REPLICATE': bool_ok,
  439. 'CLUSTER RESET': bool_ok,
  440. 'CLUSTER SAVECONFIG': bool_ok,
  441. 'CLUSTER SET-CONFIG-EPOCH': bool_ok,
  442. 'CLUSTER SETSLOT': bool_ok,
  443. 'CLUSTER SLAVES': parse_cluster_nodes,
  444. 'CONFIG GET': parse_config_get,
  445. 'CONFIG RESETSTAT': bool_ok,
  446. 'CONFIG SET': bool_ok,
  447. 'DEBUG OBJECT': parse_debug_object,
  448. 'GEOHASH': lambda r: list(map(nativestr_or_none, r)),
  449. 'GEOPOS': lambda r: list(map(lambda ll: (float(ll[0]),
  450. float(ll[1]))
  451. if ll is not None else None, r)),
  452. 'GEORADIUS': parse_georadius_generic,
  453. 'GEORADIUSBYMEMBER': parse_georadius_generic,
  454. 'HGETALL': lambda r: r and pairs_to_dict(r) or {},
  455. 'HSCAN': parse_hscan,
  456. 'INFO': parse_info,
  457. 'LASTSAVE': timestamp_to_datetime,
  458. 'MEMORY PURGE': bool_ok,
  459. 'MEMORY USAGE': int_or_none,
  460. 'OBJECT': parse_object,
  461. 'PING': lambda r: nativestr(r) == 'PONG',
  462. 'PUBSUB NUMSUB': parse_pubsub_numsub,
  463. 'RANDOMKEY': lambda r: r and r or None,
  464. 'SCAN': parse_scan,
  465. 'SCRIPT EXISTS': lambda r: list(imap(bool, r)),
  466. 'SCRIPT FLUSH': bool_ok,
  467. 'SCRIPT KILL': bool_ok,
  468. 'SCRIPT LOAD': nativestr,
  469. 'SENTINEL GET-MASTER-ADDR-BY-NAME': parse_sentinel_get_master,
  470. 'SENTINEL MASTER': parse_sentinel_master,
  471. 'SENTINEL MASTERS': parse_sentinel_masters,
  472. 'SENTINEL MONITOR': bool_ok,
  473. 'SENTINEL REMOVE': bool_ok,
  474. 'SENTINEL SENTINELS': parse_sentinel_slaves_and_sentinels,
  475. 'SENTINEL SET': bool_ok,
  476. 'SENTINEL SLAVES': parse_sentinel_slaves_and_sentinels,
  477. 'SET': lambda r: r and nativestr(r) == 'OK',
  478. 'SLOWLOG GET': parse_slowlog_get,
  479. 'SLOWLOG LEN': int,
  480. 'SLOWLOG RESET': bool_ok,
  481. 'SSCAN': parse_scan,
  482. 'TIME': lambda x: (int(x[0]), int(x[1])),
  483. 'XCLAIM': parse_xclaim,
  484. 'XGROUP CREATE': bool_ok,
  485. 'XGROUP DELCONSUMER': int,
  486. 'XGROUP DESTROY': bool,
  487. 'XGROUP SETID': bool_ok,
  488. 'XINFO CONSUMERS': parse_list_of_dicts,
  489. 'XINFO GROUPS': parse_list_of_dicts,
  490. 'XINFO STREAM': parse_xinfo_stream,
  491. 'XPENDING': parse_xpending,
  492. 'ZADD': parse_zadd,
  493. 'ZSCAN': parse_zscan,
  494. }
  495. )
  496. @classmethod
  497. def from_url(cls, url, db=None, **kwargs):
  498. """
  499. Return a Redis client object configured from the given URL
  500. For example::
  501. redis://[:password]@localhost:6379/0
  502. rediss://[:password]@localhost:6379/0
  503. unix://[:password]@/path/to/socket.sock?db=0
  504. Three URL schemes are supported:
  505. - ```redis://``
  506. <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ creates a
  507. normal TCP socket connection
  508. - ```rediss://``
  509. <http://www.iana.org/assignments/uri-schemes/prov/rediss>`_ creates a
  510. SSL wrapped TCP socket connection
  511. - ``unix://`` creates a Unix Domain Socket connection
  512. There are several ways to specify a database number. The parse function
  513. will return the first specified option:
  514. 1. A ``db`` querystring option, e.g. redis://localhost?db=0
  515. 2. If using the redis:// scheme, the path argument of the url, e.g.
  516. redis://localhost/0
  517. 3. The ``db`` argument to this function.
  518. If none of these options are specified, db=0 is used.
  519. Any additional querystring arguments and keyword arguments will be
  520. passed along to the ConnectionPool class's initializer. In the case
  521. of conflicting arguments, querystring arguments always win.
  522. """
  523. connection_pool = ConnectionPool.from_url(url, db=db, **kwargs)
  524. return cls(connection_pool=connection_pool)
  525. def __init__(self, host='localhost', port=6379,
  526. db=0, password=None, socket_timeout=None,
  527. socket_connect_timeout=None,
  528. socket_keepalive=None, socket_keepalive_options=None,
  529. connection_pool=None, unix_socket_path=None,
  530. encoding='utf-8', encoding_errors='strict',
  531. charset=None, errors=None,
  532. decode_responses=False, retry_on_timeout=False,
  533. ssl=False, ssl_keyfile=None, ssl_certfile=None,
  534. ssl_cert_reqs='required', ssl_ca_certs=None,
  535. max_connections=None, single_connection_client=False,
  536. health_check_interval=0):
  537. if not connection_pool:
  538. if charset is not None:
  539. warnings.warn(DeprecationWarning(
  540. '"charset" is deprecated. Use "encoding" instead'))
  541. encoding = charset
  542. if errors is not None:
  543. warnings.warn(DeprecationWarning(
  544. '"errors" is deprecated. Use "encoding_errors" instead'))
  545. encoding_errors = errors
  546. kwargs = {
  547. 'db': db,
  548. 'password': password,
  549. 'socket_timeout': socket_timeout,
  550. 'encoding': encoding,
  551. 'encoding_errors': encoding_errors,
  552. 'decode_responses': decode_responses,
  553. 'retry_on_timeout': retry_on_timeout,
  554. 'max_connections': max_connections,
  555. 'health_check_interval': health_check_interval,
  556. }
  557. # based on input, setup appropriate connection args
  558. if unix_socket_path is not None:
  559. kwargs.update({
  560. 'path': unix_socket_path,
  561. 'connection_class': UnixDomainSocketConnection
  562. })
  563. else:
  564. # TCP specific options
  565. kwargs.update({
  566. 'host': host,
  567. 'port': port,
  568. 'socket_connect_timeout': socket_connect_timeout,
  569. 'socket_keepalive': socket_keepalive,
  570. 'socket_keepalive_options': socket_keepalive_options,
  571. })
  572. if ssl:
  573. kwargs.update({
  574. 'connection_class': SSLConnection,
  575. 'ssl_keyfile': ssl_keyfile,
  576. 'ssl_certfile': ssl_certfile,
  577. 'ssl_cert_reqs': ssl_cert_reqs,
  578. 'ssl_ca_certs': ssl_ca_certs,
  579. })
  580. connection_pool = ConnectionPool(**kwargs)
  581. self.connection_pool = connection_pool
  582. self.connection = None
  583. if single_connection_client:
  584. self.connection = self.connection_pool.get_connection('_')
  585. self.response_callbacks = CaseInsensitiveDict(
  586. self.__class__.RESPONSE_CALLBACKS)
  587. def __repr__(self):
  588. return "%s<%s>" % (type(self).__name__, repr(self.connection_pool))
  589. def set_response_callback(self, command, callback):
  590. "Set a custom Response Callback"
  591. self.response_callbacks[command] = callback
  592. def pipeline(self, transaction=True, shard_hint=None):
  593. """
  594. Return a new pipeline object that can queue multiple commands for
  595. later execution. ``transaction`` indicates whether all commands
  596. should be executed atomically. Apart from making a group of operations
  597. atomic, pipelines are useful for reducing the back-and-forth overhead
  598. between the client and server.
  599. """
  600. return Pipeline(
  601. self.connection_pool,
  602. self.response_callbacks,
  603. transaction,
  604. shard_hint)
  605. def transaction(self, func, *watches, **kwargs):
  606. """
  607. Convenience method for executing the callable `func` as a transaction
  608. while watching all keys specified in `watches`. The 'func' callable
  609. should expect a single argument which is a Pipeline object.
  610. """
  611. shard_hint = kwargs.pop('shard_hint', None)
  612. value_from_callable = kwargs.pop('value_from_callable', False)
  613. watch_delay = kwargs.pop('watch_delay', None)
  614. with self.pipeline(True, shard_hint) as pipe:
  615. while True:
  616. try:
  617. if watches:
  618. pipe.watch(*watches)
  619. func_value = func(pipe)
  620. exec_value = pipe.execute()
  621. return func_value if value_from_callable else exec_value
  622. except WatchError:
  623. if watch_delay is not None and watch_delay > 0:
  624. time.sleep(watch_delay)
  625. continue
  626. def lock(self, name, timeout=None, sleep=0.1, blocking_timeout=None,
  627. lock_class=None, thread_local=True):
  628. """
  629. Return a new Lock object using key ``name`` that mimics
  630. the behavior of threading.Lock.
  631. If specified, ``timeout`` indicates a maximum life for the lock.
  632. By default, it will remain locked until release() is called.
  633. ``sleep`` indicates the amount of time to sleep per loop iteration
  634. when the lock is in blocking mode and another client is currently
  635. holding the lock.
  636. ``blocking_timeout`` indicates the maximum amount of time in seconds to
  637. spend trying to acquire the lock. A value of ``None`` indicates
  638. continue trying forever. ``blocking_timeout`` can be specified as a
  639. float or integer, both representing the number of seconds to wait.
  640. ``lock_class`` forces the specified lock implementation.
  641. ``thread_local`` indicates whether the lock token is placed in
  642. thread-local storage. By default, the token is placed in thread local
  643. storage so that a thread only sees its token, not a token set by
  644. another thread. Consider the following timeline:
  645. time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
  646. thread-1 sets the token to "abc"
  647. time: 1, thread-2 blocks trying to acquire `my-lock` using the
  648. Lock instance.
  649. time: 5, thread-1 has not yet completed. redis expires the lock
  650. key.
  651. time: 5, thread-2 acquired `my-lock` now that it's available.
  652. thread-2 sets the token to "xyz"
  653. time: 6, thread-1 finishes its work and calls release(). if the
  654. token is *not* stored in thread local storage, then
  655. thread-1 would see the token value as "xyz" and would be
  656. able to successfully release the thread-2's lock.
  657. In some use cases it's necessary to disable thread local storage. For
  658. example, if you have code where one thread acquires a lock and passes
  659. that lock instance to a worker thread to release later. If thread
  660. local storage isn't disabled in this case, the worker thread won't see
  661. the token set by the thread that acquired the lock. Our assumption
  662. is that these cases aren't common and as such default to using
  663. thread local storage. """
  664. if lock_class is None:
  665. lock_class = Lock
  666. return lock_class(self, name, timeout=timeout, sleep=sleep,
  667. blocking_timeout=blocking_timeout,
  668. thread_local=thread_local)
  669. def pubsub(self, **kwargs):
  670. """
  671. Return a Publish/Subscribe object. With this object, you can
  672. subscribe to channels and listen for messages that get published to
  673. them.
  674. """
  675. return PubSub(self.connection_pool, **kwargs)
  676. def monitor(self):
  677. return Monitor(self.connection_pool)
  678. def client(self):
  679. return self.__class__(connection_pool=self.connection_pool,
  680. single_connection_client=True)
  681. def __enter__(self):
  682. return self
  683. def __exit__(self, exc_type, exc_value, traceback):
  684. self.close()
  685. def __del__(self):
  686. self.close()
  687. def close(self):
  688. conn = self.connection
  689. if conn:
  690. self.connection = None
  691. self.connection_pool.release(conn)
  692. # COMMAND EXECUTION AND PROTOCOL PARSING
  693. def execute_command(self, *args, **options):
  694. "Execute a command and return a parsed response"
  695. pool = self.connection_pool
  696. command_name = args[0]
  697. conn = self.connection or pool.get_connection(command_name, **options)
  698. try:
  699. conn.send_command(*args)
  700. return self.parse_response(conn, command_name, **options)
  701. except (ConnectionError, TimeoutError) as e:
  702. conn.disconnect()
  703. if not (conn.retry_on_timeout and isinstance(e, TimeoutError)):
  704. raise
  705. conn.send_command(*args)
  706. return self.parse_response(conn, command_name, **options)
  707. finally:
  708. if not self.connection:
  709. pool.release(conn)
  710. def parse_response(self, connection, command_name, **options):
  711. "Parses a response from the Redis server"
  712. try:
  713. response = connection.read_response()
  714. except ResponseError:
  715. if EMPTY_RESPONSE in options:
  716. return options[EMPTY_RESPONSE]
  717. raise
  718. if command_name in self.response_callbacks:
  719. return self.response_callbacks[command_name](response, **options)
  720. return response
  721. # SERVER INFORMATION
  722. def bgrewriteaof(self):
  723. "Tell the Redis server to rewrite the AOF file from data in memory."
  724. return self.execute_command('BGREWRITEAOF')
  725. def bgsave(self):
  726. """
  727. Tell the Redis server to save its data to disk. Unlike save(),
  728. this method is asynchronous and returns immediately.
  729. """
  730. return self.execute_command('BGSAVE')
  731. def client_kill(self, address):
  732. "Disconnects the client at ``address`` (ip:port)"
  733. return self.execute_command('CLIENT KILL', address)
  734. def client_kill_filter(self, _id=None, _type=None, addr=None, skipme=None):
  735. """
  736. Disconnects client(s) using a variety of filter options
  737. :param id: Kills a client by its unique ID field
  738. :param type: Kills a client by type where type is one of 'normal',
  739. 'master', 'slave' or 'pubsub'
  740. :param addr: Kills a client by its 'address:port'
  741. :param skipme: If True, then the client calling the command
  742. will not get killed even if it is identified by one of the filter
  743. options. If skipme is not provided, the server defaults to skipme=True
  744. """
  745. args = []
  746. if _type is not None:
  747. client_types = ('normal', 'master', 'slave', 'pubsub')
  748. if str(_type).lower() not in client_types:
  749. raise DataError("CLIENT KILL type must be one of %r" % (
  750. client_types,))
  751. args.extend((b'TYPE', _type))
  752. if skipme is not None:
  753. if not isinstance(skipme, bool):
  754. raise DataError("CLIENT KILL skipme must be a bool")
  755. if skipme:
  756. args.extend((b'SKIPME', b'YES'))
  757. else:
  758. args.extend((b'SKIPME', b'NO'))
  759. if _id is not None:
  760. args.extend((b'ID', _id))
  761. if addr is not None:
  762. args.extend((b'ADDR', addr))
  763. if not args:
  764. raise DataError("CLIENT KILL <filter> <value> ... ... <filter> "
  765. "<value> must specify at least one filter")
  766. return self.execute_command('CLIENT KILL', *args)
  767. def client_list(self, _type=None):
  768. """
  769. Returns a list of currently connected clients.
  770. If type of client specified, only that type will be returned.
  771. :param _type: optional. one of the client types (normal, master,
  772. replica, pubsub)
  773. """
  774. "Returns a list of currently connected clients"
  775. if _type is not None:
  776. client_types = ('normal', 'master', 'replica', 'pubsub')
  777. if str(_type).lower() not in client_types:
  778. raise DataError("CLIENT LIST _type must be one of %r" % (
  779. client_types,))
  780. return self.execute_command('CLIENT LIST', b'TYPE', _type)
  781. return self.execute_command('CLIENT LIST')
  782. def client_getname(self):
  783. "Returns the current connection name"
  784. return self.execute_command('CLIENT GETNAME')
  785. def client_id(self):
  786. "Returns the current connection id"
  787. return self.execute_command('CLIENT ID')
  788. def client_setname(self, name):
  789. "Sets the current connection name"
  790. return self.execute_command('CLIENT SETNAME', name)
  791. def client_unblock(self, client_id, error=False):
  792. """
  793. Unblocks a connection by its client id.
  794. If ``error`` is True, unblocks the client with a special error message.
  795. If ``error`` is False (default), the client is unblocked using the
  796. regular timeout mechanism.
  797. """
  798. args = ['CLIENT UNBLOCK', int(client_id)]
  799. if error:
  800. args.append(b'ERROR')
  801. return self.execute_command(*args)
  802. def client_pause(self, timeout):
  803. """
  804. Suspend all the Redis clients for the specified amount of time
  805. :param timeout: milliseconds to pause clients
  806. """
  807. if not isinstance(timeout, (int, long)):
  808. raise DataError("CLIENT PAUSE timeout must be an integer")
  809. return self.execute_command('CLIENT PAUSE', str(timeout))
  810. def readwrite(self):
  811. "Disables read queries for a connection to a Redis Cluster slave node"
  812. return self.execute_command('READWRITE')
  813. def readonly(self):
  814. "Enables read queries for a connection to a Redis Cluster replica node"
  815. return self.execute_command('READONLY')
  816. def config_get(self, pattern="*"):
  817. "Return a dictionary of configuration based on the ``pattern``"
  818. return self.execute_command('CONFIG GET', pattern)
  819. def config_set(self, name, value):
  820. "Set config item ``name`` with ``value``"
  821. return self.execute_command('CONFIG SET', name, value)
  822. def config_resetstat(self):
  823. "Reset runtime statistics"
  824. return self.execute_command('CONFIG RESETSTAT')
  825. def config_rewrite(self):
  826. "Rewrite config file with the minimal change to reflect running config"
  827. return self.execute_command('CONFIG REWRITE')
  828. def dbsize(self):
  829. "Returns the number of keys in the current database"
  830. return self.execute_command('DBSIZE')
  831. def debug_object(self, key):
  832. "Returns version specific meta information about a given key"
  833. return self.execute_command('DEBUG OBJECT', key)
  834. def echo(self, value):
  835. "Echo the string back from the server"
  836. return self.execute_command('ECHO', value)
  837. def flushall(self, asynchronous=False):
  838. """
  839. Delete all keys in all databases on the current host.
  840. ``asynchronous`` indicates whether the operation is
  841. executed asynchronously by the server.
  842. """
  843. args = []
  844. if asynchronous:
  845. args.append(b'ASYNC')
  846. return self.execute_command('FLUSHALL', *args)
  847. def flushdb(self, asynchronous=False):
  848. """
  849. Delete all keys in the current database.
  850. ``asynchronous`` indicates whether the operation is
  851. executed asynchronously by the server.
  852. """
  853. args = []
  854. if asynchronous:
  855. args.append(b'ASYNC')
  856. return self.execute_command('FLUSHDB', *args)
  857. def swapdb(self, first, second):
  858. "Swap two databases"
  859. return self.execute_command('SWAPDB', first, second)
  860. def info(self, section=None):
  861. """
  862. Returns a dictionary containing information about the Redis server
  863. The ``section`` option can be used to select a specific section
  864. of information
  865. The section option is not supported by older versions of Redis Server,
  866. and will generate ResponseError
  867. """
  868. if section is None:
  869. return self.execute_command('INFO')
  870. else:
  871. return self.execute_command('INFO', section)
  872. def lastsave(self):
  873. """
  874. Return a Python datetime object representing the last time the
  875. Redis database was saved to disk
  876. """
  877. return self.execute_command('LASTSAVE')
  878. def migrate(self, host, port, keys, destination_db, timeout,
  879. copy=False, replace=False, auth=None):
  880. """
  881. Migrate 1 or more keys from the current Redis server to a different
  882. server specified by the ``host``, ``port`` and ``destination_db``.
  883. The ``timeout``, specified in milliseconds, indicates the maximum
  884. time the connection between the two servers can be idle before the
  885. command is interrupted.
  886. If ``copy`` is True, the specified ``keys`` are NOT deleted from
  887. the source server.
  888. If ``replace`` is True, this operation will overwrite the keys
  889. on the destination server if they exist.
  890. If ``auth`` is specified, authenticate to the destination server with
  891. the password provided.
  892. """
  893. keys = list_or_args(keys, [])
  894. if not keys:
  895. raise DataError('MIGRATE requires at least one key')
  896. pieces = []
  897. if copy:
  898. pieces.append(b'COPY')
  899. if replace:
  900. pieces.append(b'REPLACE')
  901. if auth:
  902. pieces.append(b'AUTH')
  903. pieces.append(auth)
  904. pieces.append(b'KEYS')
  905. pieces.extend(keys)
  906. return self.execute_command('MIGRATE', host, port, '', destination_db,
  907. timeout, *pieces)
  908. def object(self, infotype, key):
  909. "Return the encoding, idletime, or refcount about the key"
  910. return self.execute_command('OBJECT', infotype, key, infotype=infotype)
  911. def memory_usage(self, key, samples=None):
  912. """
  913. Return the total memory usage for key, its value and associated
  914. administrative overheads.
  915. For nested data structures, ``samples`` is the number of elements to
  916. sample. If left unspecified, the server's default is 5. Use 0 to sample
  917. all elements.
  918. """
  919. args = []
  920. if isinstance(samples, int):
  921. args.extend([b'SAMPLES', samples])
  922. return self.execute_command('MEMORY USAGE', key, *args)
  923. def memory_purge(self):
  924. "Attempts to purge dirty pages for reclamation by allocator"
  925. return self.execute_command('MEMORY PURGE')
  926. def ping(self):
  927. "Ping the Redis server"
  928. return self.execute_command('PING')
  929. def save(self):
  930. """
  931. Tell the Redis server to save its data to disk,
  932. blocking until the save is complete
  933. """
  934. return self.execute_command('SAVE')
  935. def sentinel(self, *args):
  936. "Redis Sentinel's SENTINEL command."
  937. warnings.warn(
  938. DeprecationWarning('Use the individual sentinel_* methods'))
  939. def sentinel_get_master_addr_by_name(self, service_name):
  940. "Returns a (host, port) pair for the given ``service_name``"
  941. return self.execute_command('SENTINEL GET-MASTER-ADDR-BY-NAME',
  942. service_name)
  943. def sentinel_master(self, service_name):
  944. "Returns a dictionary containing the specified masters state."
  945. return self.execute_command('SENTINEL MASTER', service_name)
  946. def sentinel_masters(self):
  947. "Returns a list of dictionaries containing each master's state."
  948. return self.execute_command('SENTINEL MASTERS')
  949. def sentinel_monitor(self, name, ip, port, quorum):
  950. "Add a new master to Sentinel to be monitored"
  951. return self.execute_command('SENTINEL MONITOR', name, ip, port, quorum)
  952. def sentinel_remove(self, name):
  953. "Remove a master from Sentinel's monitoring"
  954. return self.execute_command('SENTINEL REMOVE', name)
  955. def sentinel_sentinels(self, service_name):
  956. "Returns a list of sentinels for ``service_name``"
  957. return self.execute_command('SENTINEL SENTINELS', service_name)
  958. def sentinel_set(self, name, option, value):
  959. "Set Sentinel monitoring parameters for a given master"
  960. return self.execute_command('SENTINEL SET', name, option, value)
  961. def sentinel_slaves(self, service_name):
  962. "Returns a list of slaves for ``service_name``"
  963. return self.execute_command('SENTINEL SLAVES', service_name)
  964. def shutdown(self, save=False, nosave=False):
  965. """Shutdown the Redis server. If Redis has persistence configured,
  966. data will be flushed before shutdown. If the "save" option is set,
  967. a data flush will be attempted even if there is no persistence
  968. configured. If the "nosave" option is set, no data flush will be
  969. attempted. The "save" and "nosave" options cannot both be set.
  970. """
  971. if save and nosave:
  972. raise DataError('SHUTDOWN save and nosave cannot both be set')
  973. args = ['SHUTDOWN']
  974. if save:
  975. args.append('SAVE')
  976. if nosave:
  977. args.append('NOSAVE')
  978. try:
  979. self.execute_command(*args)
  980. except ConnectionError:
  981. # a ConnectionError here is expected
  982. return
  983. raise RedisError("SHUTDOWN seems to have failed.")
  984. def slaveof(self, host=None, port=None):
  985. """
  986. Set the server to be a replicated slave of the instance identified
  987. by the ``host`` and ``port``. If called without arguments, the
  988. instance is promoted to a master instead.
  989. """
  990. if host is None and port is None:
  991. return self.execute_command('SLAVEOF', b'NO', b'ONE')
  992. return self.execute_command('SLAVEOF', host, port)
  993. def slowlog_get(self, num=None):
  994. """
  995. Get the entries from the slowlog. If ``num`` is specified, get the
  996. most recent ``num`` items.
  997. """
  998. args = ['SLOWLOG GET']
  999. if num is not None:
  1000. args.append(num)
  1001. return self.execute_command(*args)
  1002. def slowlog_len(self):
  1003. "Get the number of items in the slowlog"
  1004. return self.execute_command('SLOWLOG LEN')
  1005. def slowlog_reset(self):
  1006. "Remove all items in the slowlog"
  1007. return self.execute_command('SLOWLOG RESET')
  1008. def time(self):
  1009. """
  1010. Returns the server time as a 2-item tuple of ints:
  1011. (seconds since epoch, microseconds into this second).
  1012. """
  1013. return self.execute_command('TIME')
  1014. def wait(self, num_replicas, timeout):
  1015. """
  1016. Redis synchronous replication
  1017. That returns the number of replicas that processed the query when
  1018. we finally have at least ``num_replicas``, or when the ``timeout`` was
  1019. reached.
  1020. """
  1021. return self.execute_command('WAIT', num_replicas, timeout)
  1022. # BASIC KEY COMMANDS
  1023. def append(self, key, value):
  1024. """
  1025. Appends the string ``value`` to the value at ``key``. If ``key``
  1026. doesn't already exist, create it with a value of ``value``.
  1027. Returns the new length of the value at ``key``.
  1028. """
  1029. return self.execute_command('APPEND', key, value)
  1030. def bitcount(self, key, start=None, end=None):
  1031. """
  1032. Returns the count of set bits in the value of ``key``. Optional
  1033. ``start`` and ``end`` paramaters indicate which bytes to consider
  1034. """
  1035. params = [key]
  1036. if start is not None and end is not None:
  1037. params.append(start)
  1038. params.append(end)
  1039. elif (start is not None and end is None) or \
  1040. (end is not None and start is None):
  1041. raise DataError("Both start and end must be specified")
  1042. return self.execute_command('BITCOUNT', *params)
  1043. def bitfield(self, key, default_overflow=None):
  1044. """
  1045. Return a BitFieldOperation instance to conveniently construct one or
  1046. more bitfield operations on ``key``.
  1047. """
  1048. return BitFieldOperation(self, key, default_overflow=default_overflow)
  1049. def bitop(self, operation, dest, *keys):
  1050. """
  1051. Perform a bitwise operation using ``operation`` between ``keys`` and
  1052. store the result in ``dest``.
  1053. """
  1054. return self.execute_command('BITOP', operation, dest, *keys)
  1055. def bitpos(self, key, bit, start=None, end=None):
  1056. """
  1057. Return the position of the first bit set to 1 or 0 in a string.
  1058. ``start`` and ``end`` difines search range. The range is interpreted
  1059. as a range of bytes and not a range of bits, so start=0 and end=2
  1060. means to look at the first three bytes.
  1061. """
  1062. if bit not in (0, 1):
  1063. raise DataError('bit must be 0 or 1')
  1064. params = [key, bit]
  1065. start is not None and params.append(start)
  1066. if start is not None and end is not None:
  1067. params.append(end)
  1068. elif start is None and end is not None:
  1069. raise DataError("start argument is not set, "
  1070. "when end is specified")
  1071. return self.execute_command('BITPOS', *params)
  1072. def decr(self, name, amount=1):
  1073. """
  1074. Decrements the value of ``key`` by ``amount``. If no key exists,
  1075. the value will be initialized as 0 - ``amount``
  1076. """
  1077. # An alias for ``decr()``, because it is already implemented
  1078. # as DECRBY redis command.
  1079. return self.decrby(name, amount)
  1080. def decrby(self, name, amount=1):
  1081. """
  1082. Decrements the value of ``key`` by ``amount``. If no key exists,
  1083. the value will be initialized as 0 - ``amount``
  1084. """
  1085. return self.execute_command('DECRBY', name, amount)
  1086. def delete(self, *names):
  1087. "Delete one or more keys specified by ``names``"
  1088. return self.execute_command('DEL', *names)
  1089. def __delitem__(self, name):
  1090. self.delete(name)
  1091. def dump(self, name):
  1092. """
  1093. Return a serialized version of the value stored at the specified key.
  1094. If key does not exist a nil bulk reply is returned.
  1095. """
  1096. return self.execute_command('DUMP', name)
  1097. def exists(self, *names):
  1098. "Returns the number of ``names`` that exist"
  1099. return self.execute_command('EXISTS', *names)
  1100. __contains__ = exists
  1101. def expire(self, name, time):
  1102. """
  1103. Set an expire flag on key ``name`` for ``time`` seconds. ``time``
  1104. can be represented by an integer or a Python timedelta object.
  1105. """
  1106. if isinstance(time, datetime.timedelta):
  1107. time = int(time.total_seconds())
  1108. return self.execute_command('EXPIRE', name, time)
  1109. def expireat(self, name, when):
  1110. """
  1111. Set an expire flag on key ``name``. ``when`` can be represented
  1112. as an integer indicating unix time or a Python datetime object.
  1113. """
  1114. if isinstance(when, datetime.datetime):
  1115. when = int(mod_time.mktime(when.timetuple()))
  1116. return self.execute_command('EXPIREAT', name, when)
  1117. def get(self, name):
  1118. """
  1119. Return the value at key ``name``, or None if the key doesn't exist
  1120. """
  1121. return self.execute_command('GET', name)
  1122. def __getitem__(self, name):
  1123. """
  1124. Return the value at key ``name``, raises a KeyError if the key
  1125. doesn't exist.
  1126. """
  1127. value = self.get(name)
  1128. if value is not None:
  1129. return value
  1130. raise KeyError(name)
  1131. def getbit(self, name, offset):
  1132. "Returns a boolean indicating the value of ``offset`` in ``name``"
  1133. return self.execute_command('GETBIT', name, offset)
  1134. def getrange(self, key, start, end):
  1135. """
  1136. Returns the substring of the string value stored at ``key``,
  1137. determined by the offsets ``start`` and ``end`` (both are inclusive)
  1138. """
  1139. return self.execute_command('GETRANGE', key, start, end)
  1140. def getset(self, name, value):
  1141. """
  1142. Sets the value at key ``name`` to ``value``
  1143. and returns the old value at key ``name`` atomically.
  1144. """
  1145. return self.execute_command('GETSET', name, value)
  1146. def incr(self, name, amount=1):
  1147. """
  1148. Increments the value of ``key`` by ``amount``. If no key exists,
  1149. the value will be initialized as ``amount``
  1150. """
  1151. return self.incrby(name, amount)
  1152. def incrby(self, name, amount=1):
  1153. """
  1154. Increments the value of ``key`` by ``amount``. If no key exists,
  1155. the value will be initialized as ``amount``
  1156. """
  1157. # An alias for ``incr()``, because it is already implemented
  1158. # as INCRBY redis command.
  1159. return self.execute_command('INCRBY', name, amount)
  1160. def incrbyfloat(self, name, amount=1.0):
  1161. """
  1162. Increments the value at key ``name`` by floating ``amount``.
  1163. If no key exists, the value will be initialized as ``amount``
  1164. """
  1165. return self.execute_command('INCRBYFLOAT', name, amount)
  1166. def keys(self, pattern='*'):
  1167. "Returns a list of keys matching ``pattern``"
  1168. return self.execute_command('KEYS', pattern)
  1169. def mget(self, keys, *args):
  1170. """
  1171. Returns a list of values ordered identically to ``keys``
  1172. """
  1173. args = list_or_args(keys, args)
  1174. options = {}
  1175. if not args:
  1176. options[EMPTY_RESPONSE] = []
  1177. return self.execute_command('MGET', *args, **options)
  1178. def mset(self, mapping):
  1179. """
  1180. Sets key/values based on a mapping. Mapping is a dictionary of
  1181. key/value pairs. Both keys and values should be strings or types that
  1182. can be cast to a string via str().
  1183. """
  1184. items = []
  1185. for pair in iteritems(mapping):
  1186. items.extend(pair)
  1187. return self.execute_command('MSET', *items)
  1188. def msetnx(self, mapping):
  1189. """
  1190. Sets key/values based on a mapping if none of the keys are already set.
  1191. Mapping is a dictionary of key/value pairs. Both keys and values
  1192. should be strings or types that can be cast to a string via str().
  1193. Returns a boolean indicating if the operation was successful.
  1194. """
  1195. items = []
  1196. for pair in iteritems(mapping):
  1197. items.extend(pair)
  1198. return self.execute_command('MSETNX', *items)
  1199. def move(self, name, db):
  1200. "Moves the key ``name`` to a different Redis database ``db``"
  1201. return self.execute_command('MOVE', name, db)
  1202. def persist(self, name):
  1203. "Removes an expiration on ``name``"
  1204. return self.execute_command('PERSIST', name)
  1205. def pexpire(self, name, time):
  1206. """
  1207. Set an expire flag on key ``name`` for ``time`` milliseconds.
  1208. ``time`` can be represented by an integer or a Python timedelta
  1209. object.
  1210. """
  1211. if isinstance(time, datetime.timedelta):
  1212. time = int(time.total_seconds() * 1000)
  1213. return self.execute_command('PEXPIRE', name, time)
  1214. def pexpireat(self, name, when):
  1215. """
  1216. Set an expire flag on key ``name``. ``when`` can be represented
  1217. as an integer representing unix time in milliseconds (unix time * 1000)
  1218. or a Python datetime object.
  1219. """
  1220. if isinstance(when, datetime.datetime):
  1221. ms = int(when.microsecond / 1000)
  1222. when = int(mod_time.mktime(when.timetuple())) * 1000 + ms
  1223. return self.execute_command('PEXPIREAT', name, when)
  1224. def psetex(self, name, time_ms, value):
  1225. """
  1226. Set the value of key ``name`` to ``value`` that expires in ``time_ms``
  1227. milliseconds. ``time_ms`` can be represented by an integer or a Python
  1228. timedelta object
  1229. """
  1230. if isinstance(time_ms, datetime.timedelta):
  1231. time_ms = int(time_ms.total_seconds() * 1000)
  1232. return self.execute_command('PSETEX', name, time_ms, value)
  1233. def pttl(self, name):
  1234. "Returns the number of milliseconds until the key ``name`` will expire"
  1235. return self.execute_command('PTTL', name)
  1236. def randomkey(self):
  1237. "Returns the name of a random key"
  1238. return self.execute_command('RANDOMKEY')
  1239. def rename(self, src, dst):
  1240. """
  1241. Rename key ``src`` to ``dst``
  1242. """
  1243. return self.execute_command('RENAME', src, dst)
  1244. def renamenx(self, src, dst):
  1245. "Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist"
  1246. return self.execute_command('RENAMENX', src, dst)
  1247. def restore(self, name, ttl, value, replace=False):
  1248. """
  1249. Create a key using the provided serialized value, previously obtained
  1250. using DUMP.
  1251. """
  1252. params = [name, ttl, value]
  1253. if replace:
  1254. params.append('REPLACE')
  1255. return self.execute_command('RESTORE', *params)
  1256. def set(self, name, value, ex=None, px=None, nx=False, xx=False):
  1257. """
  1258. Set the value at key ``name`` to ``value``
  1259. ``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.
  1260. ``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.
  1261. ``nx`` if set to True, set the value at key ``name`` to ``value`` only
  1262. if it does not exist.
  1263. ``xx`` if set to True, set the value at key ``name`` to ``value`` only
  1264. if it already exists.
  1265. """
  1266. pieces = [name, value]
  1267. if ex is not None:
  1268. pieces.append('EX')
  1269. if isinstance(ex, datetime.timedelta):
  1270. ex = int(ex.total_seconds())
  1271. pieces.append(ex)
  1272. if px is not None:
  1273. pieces.append('PX')
  1274. if isinstance(px, datetime.timedelta):
  1275. px = int(px.total_seconds() * 1000)
  1276. pieces.append(px)
  1277. if nx:
  1278. pieces.append('NX')
  1279. if xx:
  1280. pieces.append('XX')
  1281. return self.execute_command('SET', *pieces)
  1282. def __setitem__(self, name, value):
  1283. self.set(name, value)
  1284. def setbit(self, name, offset, value):
  1285. """
  1286. Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
  1287. indicating the previous value of ``offset``.
  1288. """
  1289. value = value and 1 or 0
  1290. return self.execute_command('SETBIT', name, offset, value)
  1291. def setex(self, name, time, value):
  1292. """
  1293. Set the value of key ``name`` to ``value`` that expires in ``time``
  1294. seconds. ``time`` can be represented by an integer or a Python
  1295. timedelta object.
  1296. """
  1297. if isinstance(time, datetime.timedelta):
  1298. time = int(time.total_seconds())
  1299. return self.execute_command('SETEX', name, time, value)
  1300. def setnx(self, name, value):
  1301. "Set the value of key ``name`` to ``value`` if key doesn't exist"
  1302. return self.execute_command('SETNX', name, value)
  1303. def setrange(self, name, offset, value):
  1304. """
  1305. Overwrite bytes in the value of ``name`` starting at ``offset`` with
  1306. ``value``. If ``offset`` plus the length of ``value`` exceeds the
  1307. length of the original value, the new value will be larger than before.
  1308. If ``offset`` exceeds the length of the original value, null bytes
  1309. will be used to pad between the end of the previous value and the start
  1310. of what's being injected.
  1311. Returns the length of the new string.
  1312. """
  1313. return self.execute_command('SETRANGE', name, offset, value)
  1314. def strlen(self, name):
  1315. "Return the number of bytes stored in the value of ``name``"
  1316. return self.execute_command('STRLEN', name)
  1317. def substr(self, name, start, end=-1):
  1318. """
  1319. Return a substring of the string at key ``name``. ``start`` and ``end``
  1320. are 0-based integers specifying the portion of the string to return.
  1321. """
  1322. return self.execute_command('SUBSTR', name, start, end)
  1323. def touch(self, *args):
  1324. """
  1325. Alters the last access time of a key(s) ``*args``. A key is ignored
  1326. if it does not exist.
  1327. """
  1328. return self.execute_command('TOUCH', *args)
  1329. def ttl(self, name):
  1330. "Returns the number of seconds until the key ``name`` will expire"
  1331. return self.execute_command('TTL', name)
  1332. def type(self, name):
  1333. "Returns the type of key ``name``"
  1334. return self.execute_command('TYPE', name)
  1335. def watch(self, *names):
  1336. """
  1337. Watches the values at keys ``names``, or None if the key doesn't exist
  1338. """
  1339. warnings.warn(DeprecationWarning('Call WATCH from a Pipeline object'))
  1340. def unwatch(self):
  1341. """
  1342. Unwatches the value at key ``name``, or None of the key doesn't exist
  1343. """
  1344. warnings.warn(
  1345. DeprecationWarning('Call UNWATCH from a Pipeline object'))
  1346. def unlink(self, *names):
  1347. "Unlink one or more keys specified by ``names``"
  1348. return self.execute_command('UNLINK', *names)
  1349. # LIST COMMANDS
  1350. def blpop(self, keys, timeout=0):
  1351. """
  1352. LPOP a value off of the first non-empty list
  1353. named in the ``keys`` list.
  1354. If none of the lists in ``keys`` has a value to LPOP, then block
  1355. for ``timeout`` seconds, or until a value gets pushed on to one
  1356. of the lists.
  1357. If timeout is 0, then block indefinitely.
  1358. """
  1359. if timeout is None:
  1360. timeout = 0
  1361. keys = list_or_args(keys, None)
  1362. keys.append(timeout)
  1363. return self.execute_command('BLPOP', *keys)
  1364. def brpop(self, keys, timeout=0):
  1365. """
  1366. RPOP a value off of the first non-empty list
  1367. named in the ``keys`` list.
  1368. If none of the lists in ``keys`` has a value to RPOP, then block
  1369. for ``timeout`` seconds, or until a value gets pushed on to one
  1370. of the lists.
  1371. If timeout is 0, then block indefinitely.
  1372. """
  1373. if timeout is None:
  1374. timeout = 0
  1375. keys = list_or_args(keys, None)
  1376. keys.append(timeout)
  1377. return self.execute_command('BRPOP', *keys)
  1378. def brpoplpush(self, src, dst, timeout=0):
  1379. """
  1380. Pop a value off the tail of ``src``, push it on the head of ``dst``
  1381. and then return it.
  1382. This command blocks until a value is in ``src`` or until ``timeout``
  1383. seconds elapse, whichever is first. A ``timeout`` value of 0 blocks
  1384. forever.
  1385. """
  1386. if timeout is None:
  1387. timeout = 0
  1388. return self.execute_command('BRPOPLPUSH', src, dst, timeout)
  1389. def lindex(self, name, index):
  1390. """
  1391. Return the item from list ``name`` at position ``index``
  1392. Negative indexes are supported and will return an item at the
  1393. end of the list
  1394. """
  1395. return self.execute_command('LINDEX', name, index)
  1396. def linsert(self, name, where, refvalue, value):
  1397. """
  1398. Insert ``value`` in list ``name`` either immediately before or after
  1399. [``where``] ``refvalue``
  1400. Returns the new length of the list on success or -1 if ``refvalue``
  1401. is not in the list.
  1402. """
  1403. return self.execute_command('LINSERT', name, where, refvalue, value)
  1404. def llen(self, name):
  1405. "Return the length of the list ``name``"
  1406. return self.execute_command('LLEN', name)
  1407. def lpop(self, name):
  1408. "Remove and return the first item of the list ``name``"
  1409. return self.execute_command('LPOP', name)
  1410. def lpush(self, name, *values):
  1411. "Push ``values`` onto the head of the list ``name``"
  1412. return self.execute_command('LPUSH', name, *values)
  1413. def lpushx(self, name, value):
  1414. "Push ``value`` onto the head of the list ``name`` if ``name`` exists"
  1415. return self.execute_command('LPUSHX', name, value)
  1416. def lrange(self, name, start, end):
  1417. """
  1418. Return a slice of the list ``name`` between
  1419. position ``start`` and ``end``
  1420. ``start`` and ``end`` can be negative numbers just like
  1421. Python slicing notation
  1422. """
  1423. return self.execute_command('LRANGE', name, start, end)
  1424. def lrem(self, name, count, value):
  1425. """
  1426. Remove the first ``count`` occurrences of elements equal to ``value``
  1427. from the list stored at ``name``.
  1428. The count argument influences the operation in the following ways:
  1429. count > 0: Remove elements equal to value moving from head to tail.
  1430. count < 0: Remove elements equal to value moving from tail to head.
  1431. count = 0: Remove all elements equal to value.
  1432. """
  1433. return self.execute_command('LREM', name, count, value)
  1434. def lset(self, name, index, value):
  1435. "Set ``position`` of list ``name`` to ``value``"
  1436. return self.execute_command('LSET', name, index, value)
  1437. def ltrim(self, name, start, end):
  1438. """
  1439. Trim the list ``name``, removing all values not within the slice
  1440. between ``start`` and ``end``
  1441. ``start`` and ``end`` can be negative numbers just like
  1442. Python slicing notation
  1443. """
  1444. return self.execute_command('LTRIM', name, start, end)
  1445. def rpop(self, name):
  1446. "Remove and return the last item of the list ``name``"
  1447. return self.execute_command('RPOP', name)
  1448. def rpoplpush(self, src, dst):
  1449. """
  1450. RPOP a value off of the ``src`` list and atomically LPUSH it
  1451. on to the ``dst`` list. Returns the value.
  1452. """
  1453. return self.execute_command('RPOPLPUSH', src, dst)
  1454. def rpush(self, name, *values):
  1455. "Push ``values`` onto the tail of the list ``name``"
  1456. return self.execute_command('RPUSH', name, *values)
  1457. def rpushx(self, name, value):
  1458. "Push ``value`` onto the tail of the list ``name`` if ``name`` exists"
  1459. return self.execute_command('RPUSHX', name, value)
  1460. def sort(self, name, start=None, num=None, by=None, get=None,
  1461. desc=False, alpha=False, store=None, groups=False):
  1462. """
  1463. Sort and return the list, set or sorted set at ``name``.
  1464. ``start`` and ``num`` allow for paging through the sorted data
  1465. ``by`` allows using an external key to weight and sort the items.
  1466. Use an "*" to indicate where in the key the item value is located
  1467. ``get`` allows for returning items from external keys rather than the
  1468. sorted data itself. Use an "*" to indicate where int he key
  1469. the item value is located
  1470. ``desc`` allows for reversing the sort
  1471. ``alpha`` allows for sorting lexicographically rather than numerically
  1472. ``store`` allows for storing the result of the sort into
  1473. the key ``store``
  1474. ``groups`` if set to True and if ``get`` contains at least two
  1475. elements, sort will return a list of tuples, each containing the
  1476. values fetched from the arguments to ``get``.
  1477. """
  1478. if (start is not None and num is None) or \
  1479. (num is not None and start is None):
  1480. raise DataError("``start`` and ``num`` must both be specified")
  1481. pieces = [name]
  1482. if by is not None:
  1483. pieces.append(b'BY')
  1484. pieces.append(by)
  1485. if start is not None and num is not None:
  1486. pieces.append(b'LIMIT')
  1487. pieces.append(start)
  1488. pieces.append(num)
  1489. if get is not None:
  1490. # If get is a string assume we want to get a single value.
  1491. # Otherwise assume it's an interable and we want to get multiple
  1492. # values. We can't just iterate blindly because strings are
  1493. # iterable.
  1494. if isinstance(get, (bytes, basestring)):
  1495. pieces.append(b'GET')
  1496. pieces.append(get)
  1497. else:
  1498. for g in get:
  1499. pieces.append(b'GET')
  1500. pieces.append(g)
  1501. if desc:
  1502. pieces.append(b'DESC')
  1503. if alpha:
  1504. pieces.append(b'ALPHA')
  1505. if store is not None:
  1506. pieces.append(b'STORE')
  1507. pieces.append(store)
  1508. if groups:
  1509. if not get or isinstance(get, (bytes, basestring)) or len(get) < 2:
  1510. raise DataError('when using "groups" the "get" argument '
  1511. 'must be specified and contain at least '
  1512. 'two keys')
  1513. options = {'groups': len(get) if groups else None}
  1514. return self.execute_command('SORT', *pieces, **options)
  1515. # SCAN COMMANDS
  1516. def scan(self, cursor=0, match=None, count=None):
  1517. """
  1518. Incrementally return lists of key names. Also return a cursor
  1519. indicating the scan position.
  1520. ``match`` allows for filtering the keys by pattern
  1521. ``count`` allows for hint the minimum number of returns
  1522. """
  1523. pieces = [cursor]
  1524. if match is not None:
  1525. pieces.extend([b'MATCH', match])
  1526. if count is not None:
  1527. pieces.extend([b'COUNT', count])
  1528. return self.execute_command('SCAN', *pieces)
  1529. def scan_iter(self, match=None, count=None):
  1530. """
  1531. Make an iterator using the SCAN command so that the client doesn't
  1532. need to remember the cursor position.
  1533. ``match`` allows for filtering the keys by pattern
  1534. ``count`` allows for hint the minimum number of returns
  1535. """
  1536. cursor = '0'
  1537. while cursor != 0:
  1538. cursor, data = self.scan(cursor=cursor, match=match, count=count)
  1539. for item in data:
  1540. yield item
  1541. def sscan(self, name, cursor=0, match=None, count=None):
  1542. """
  1543. Incrementally return lists of elements in a set. Also return a cursor
  1544. indicating the scan position.
  1545. ``match`` allows for filtering the keys by pattern
  1546. ``count`` allows for hint the minimum number of returns
  1547. """
  1548. pieces = [name, cursor]
  1549. if match is not None:
  1550. pieces.extend([b'MATCH', match])
  1551. if count is not None:
  1552. pieces.extend([b'COUNT', count])
  1553. return self.execute_command('SSCAN', *pieces)
  1554. def sscan_iter(self, name, match=None, count=None):
  1555. """
  1556. Make an iterator using the SSCAN command so that the client doesn't
  1557. need to remember the cursor position.
  1558. ``match`` allows for filtering the keys by pattern
  1559. ``count`` allows for hint the minimum number of returns
  1560. """
  1561. cursor = '0'
  1562. while cursor != 0:
  1563. cursor, data = self.sscan(name, cursor=cursor,
  1564. match=match, count=count)
  1565. for item in data:
  1566. yield item
  1567. def hscan(self, name, cursor=0, match=None, count=None):
  1568. """
  1569. Incrementally return key/value slices in a hash. Also return a cursor
  1570. indicating the scan position.
  1571. ``match`` allows for filtering the keys by pattern
  1572. ``count`` allows for hint the minimum number of returns
  1573. """
  1574. pieces = [name, cursor]
  1575. if match is not None:
  1576. pieces.extend([b'MATCH', match])
  1577. if count is not None:
  1578. pieces.extend([b'COUNT', count])
  1579. return self.execute_command('HSCAN', *pieces)
  1580. def hscan_iter(self, name, match=None, count=None):
  1581. """
  1582. Make an iterator using the HSCAN command so that the client doesn't
  1583. need to remember the cursor position.
  1584. ``match`` allows for filtering the keys by pattern
  1585. ``count`` allows for hint the minimum number of returns
  1586. """
  1587. cursor = '0'
  1588. while cursor != 0:
  1589. cursor, data = self.hscan(name, cursor=cursor,
  1590. match=match, count=count)
  1591. for item in data.items():
  1592. yield item
  1593. def zscan(self, name, cursor=0, match=None, count=None,
  1594. score_cast_func=float):
  1595. """
  1596. Incrementally return lists of elements in a sorted set. Also return a
  1597. cursor indicating the scan position.
  1598. ``match`` allows for filtering the keys by pattern
  1599. ``count`` allows for hint the minimum number of returns
  1600. ``score_cast_func`` a callable used to cast the score return value
  1601. """
  1602. pieces = [name, cursor]
  1603. if match is not None:
  1604. pieces.extend([b'MATCH', match])
  1605. if count is not None:
  1606. pieces.extend([b'COUNT', count])
  1607. options = {'score_cast_func': score_cast_func}
  1608. return self.execute_command('ZSCAN', *pieces, **options)
  1609. def zscan_iter(self, name, match=None, count=None,
  1610. score_cast_func=float):
  1611. """
  1612. Make an iterator using the ZSCAN command so that the client doesn't
  1613. need to remember the cursor position.
  1614. ``match`` allows for filtering the keys by pattern
  1615. ``count`` allows for hint the minimum number of returns
  1616. ``score_cast_func`` a callable used to cast the score return value
  1617. """
  1618. cursor = '0'
  1619. while cursor != 0:
  1620. cursor, data = self.zscan(name, cursor=cursor, match=match,
  1621. count=count,
  1622. score_cast_func=score_cast_func)
  1623. for item in data:
  1624. yield item
  1625. # SET COMMANDS
  1626. def sadd(self, name, *values):
  1627. "Add ``value(s)`` to set ``name``"
  1628. return self.execute_command('SADD', name, *values)
  1629. def scard(self, name):
  1630. "Return the number of elements in set ``name``"
  1631. return self.execute_command('SCARD', name)
  1632. def sdiff(self, keys, *args):
  1633. "Return the difference of sets specified by ``keys``"
  1634. args = list_or_args(keys, args)
  1635. return self.execute_command('SDIFF', *args)
  1636. def sdiffstore(self, dest, keys, *args):
  1637. """
  1638. Store the difference of sets specified by ``keys`` into a new
  1639. set named ``dest``. Returns the number of keys in the new set.
  1640. """
  1641. args = list_or_args(keys, args)
  1642. return self.execute_command('SDIFFSTORE', dest, *args)
  1643. def sinter(self, keys, *args):
  1644. "Return the intersection of sets specified by ``keys``"
  1645. args = list_or_args(keys, args)
  1646. return self.execute_command('SINTER', *args)
  1647. def sinterstore(self, dest, keys, *args):
  1648. """
  1649. Store the intersection of sets specified by ``keys`` into a new
  1650. set named ``dest``. Returns the number of keys in the new set.
  1651. """
  1652. args = list_or_args(keys, args)
  1653. return self.execute_command('SINTERSTORE', dest, *args)
  1654. def sismember(self, name, value):
  1655. "Return a boolean indicating if ``value`` is a member of set ``name``"
  1656. return self.execute_command('SISMEMBER', name, value)
  1657. def smembers(self, name):
  1658. "Return all members of the set ``name``"
  1659. return self.execute_command('SMEMBERS', name)
  1660. def smove(self, src, dst, value):
  1661. "Move ``value`` from set ``src`` to set ``dst`` atomically"
  1662. return self.execute_command('SMOVE', src, dst, value)
  1663. def spop(self, name, count=None):
  1664. "Remove and return a random member of set ``name``"
  1665. args = (count is not None) and [count] or []
  1666. return self.execute_command('SPOP', name, *args)
  1667. def srandmember(self, name, number=None):
  1668. """
  1669. If ``number`` is None, returns a random member of set ``name``.
  1670. If ``number`` is supplied, returns a list of ``number`` random
  1671. memebers of set ``name``. Note this is only available when running
  1672. Redis 2.6+.
  1673. """
  1674. args = (number is not None) and [number] or []
  1675. return self.execute_command('SRANDMEMBER', name, *args)
  1676. def srem(self, name, *values):
  1677. "Remove ``values`` from set ``name``"
  1678. return self.execute_command('SREM', name, *values)
  1679. def sunion(self, keys, *args):
  1680. "Return the union of sets specified by ``keys``"
  1681. args = list_or_args(keys, args)
  1682. return self.execute_command('SUNION', *args)
  1683. def sunionstore(self, dest, keys, *args):
  1684. """
  1685. Store the union of sets specified by ``keys`` into a new
  1686. set named ``dest``. Returns the number of keys in the new set.
  1687. """
  1688. args = list_or_args(keys, args)
  1689. return self.execute_command('SUNIONSTORE', dest, *args)
  1690. # STREAMS COMMANDS
  1691. def xack(self, name, groupname, *ids):
  1692. """
  1693. Acknowledges the successful processing of one or more messages.
  1694. name: name of the stream.
  1695. groupname: name of the consumer group.
  1696. *ids: message ids to acknowlege.
  1697. """
  1698. return self.execute_command('XACK', name, groupname, *ids)
  1699. def xadd(self, name, fields, id='*', maxlen=None, approximate=True):
  1700. """
  1701. Add to a stream.
  1702. name: name of the stream
  1703. fields: dict of field/value pairs to insert into the stream
  1704. id: Location to insert this record. By default it is appended.
  1705. maxlen: truncate old stream members beyond this size
  1706. approximate: actual stream length may be slightly more than maxlen
  1707. """
  1708. pieces = []
  1709. if maxlen is not None:
  1710. if not isinstance(maxlen, (int, long)) or maxlen < 1:
  1711. raise DataError('XADD maxlen must be a positive integer')
  1712. pieces.append(b'MAXLEN')
  1713. if approximate:
  1714. pieces.append(b'~')
  1715. pieces.append(str(maxlen))
  1716. pieces.append(id)
  1717. if not isinstance(fields, dict) or len(fields) == 0:
  1718. raise DataError('XADD fields must be a non-empty dict')
  1719. for pair in iteritems(fields):
  1720. pieces.extend(pair)
  1721. return self.execute_command('XADD', name, *pieces)
  1722. def xclaim(self, name, groupname, consumername, min_idle_time, message_ids,
  1723. idle=None, time=None, retrycount=None, force=False,
  1724. justid=False):
  1725. """
  1726. Changes the ownership of a pending message.
  1727. name: name of the stream.
  1728. groupname: name of the consumer group.
  1729. consumername: name of a consumer that claims the message.
  1730. min_idle_time: filter messages that were idle less than this amount of
  1731. milliseconds
  1732. message_ids: non-empty list or tuple of message IDs to claim
  1733. idle: optional. Set the idle time (last time it was delivered) of the
  1734. message in ms
  1735. time: optional integer. This is the same as idle but instead of a
  1736. relative amount of milliseconds, it sets the idle time to a specific
  1737. Unix time (in milliseconds).
  1738. retrycount: optional integer. set the retry counter to the specified
  1739. value. This counter is incremented every time a message is delivered
  1740. again.
  1741. force: optional boolean, false by default. Creates the pending message
  1742. entry in the PEL even if certain specified IDs are not already in the
  1743. PEL assigned to a different client.
  1744. justid: optional boolean, false by default. Return just an array of IDs
  1745. of messages successfully claimed, without returning the actual message
  1746. """
  1747. if not isinstance(min_idle_time, (int, long)) or min_idle_time < 0:
  1748. raise DataError("XCLAIM min_idle_time must be a non negative "
  1749. "integer")
  1750. if not isinstance(message_ids, (list, tuple)) or not message_ids:
  1751. raise DataError("XCLAIM message_ids must be a non empty list or "
  1752. "tuple of message IDs to claim")
  1753. kwargs = {}
  1754. pieces = [name, groupname, consumername, str(min_idle_time)]
  1755. pieces.extend(list(message_ids))
  1756. if idle is not None:
  1757. if not isinstance(idle, (int, long)):
  1758. raise DataError("XCLAIM idle must be an integer")
  1759. pieces.extend((b'IDLE', str(idle)))
  1760. if time is not None:
  1761. if not isinstance(time, (int, long)):
  1762. raise DataError("XCLAIM time must be an integer")
  1763. pieces.extend((b'TIME', str(time)))
  1764. if retrycount is not None:
  1765. if not isinstance(retrycount, (int, long)):
  1766. raise DataError("XCLAIM retrycount must be an integer")
  1767. pieces.extend((b'RETRYCOUNT', str(retrycount)))
  1768. if force:
  1769. if not isinstance(force, bool):
  1770. raise DataError("XCLAIM force must be a boolean")
  1771. pieces.append(b'FORCE')
  1772. if justid:
  1773. if not isinstance(justid, bool):
  1774. raise DataError("XCLAIM justid must be a boolean")
  1775. pieces.append(b'JUSTID')
  1776. kwargs['parse_justid'] = True
  1777. return self.execute_command('XCLAIM', *pieces, **kwargs)
  1778. def xdel(self, name, *ids):
  1779. """
  1780. Deletes one or more messages from a stream.
  1781. name: name of the stream.
  1782. *ids: message ids to delete.
  1783. """
  1784. return self.execute_command('XDEL', name, *ids)
  1785. def xgroup_create(self, name, groupname, id='$', mkstream=False):
  1786. """
  1787. Create a new consumer group associated with a stream.
  1788. name: name of the stream.
  1789. groupname: name of the consumer group.
  1790. id: ID of the last item in the stream to consider already delivered.
  1791. """
  1792. pieces = ['XGROUP CREATE', name, groupname, id]
  1793. if mkstream:
  1794. pieces.append(b'MKSTREAM')
  1795. return self.execute_command(*pieces)
  1796. def xgroup_delconsumer(self, name, groupname, consumername):
  1797. """
  1798. Remove a specific consumer from a consumer group.
  1799. Returns the number of pending messages that the consumer had before it
  1800. was deleted.
  1801. name: name of the stream.
  1802. groupname: name of the consumer group.
  1803. consumername: name of consumer to delete
  1804. """
  1805. return self.execute_command('XGROUP DELCONSUMER', name, groupname,
  1806. consumername)
  1807. def xgroup_destroy(self, name, groupname):
  1808. """
  1809. Destroy a consumer group.
  1810. name: name of the stream.
  1811. groupname: name of the consumer group.
  1812. """
  1813. return self.execute_command('XGROUP DESTROY', name, groupname)
  1814. def xgroup_setid(self, name, groupname, id):
  1815. """
  1816. Set the consumer group last delivered ID to something else.
  1817. name: name of the stream.
  1818. groupname: name of the consumer group.
  1819. id: ID of the last item in the stream to consider already delivered.
  1820. """
  1821. return self.execute_command('XGROUP SETID', name, groupname, id)
  1822. def xinfo_consumers(self, name, groupname):
  1823. """
  1824. Returns general information about the consumers in the group.
  1825. name: name of the stream.
  1826. groupname: name of the consumer group.
  1827. """
  1828. return self.execute_command('XINFO CONSUMERS', name, groupname)
  1829. def xinfo_groups(self, name):
  1830. """
  1831. Returns general information about the consumer groups of the stream.
  1832. name: name of the stream.
  1833. """
  1834. return self.execute_command('XINFO GROUPS', name)
  1835. def xinfo_stream(self, name):
  1836. """
  1837. Returns general information about the stream.
  1838. name: name of the stream.
  1839. """
  1840. return self.execute_command('XINFO STREAM', name)
  1841. def xlen(self, name):
  1842. """
  1843. Returns the number of elements in a given stream.
  1844. """
  1845. return self.execute_command('XLEN', name)
  1846. def xpending(self, name, groupname):
  1847. """
  1848. Returns information about pending messages of a group.
  1849. name: name of the stream.
  1850. groupname: name of the consumer group.
  1851. """
  1852. return self.execute_command('XPENDING', name, groupname)
  1853. def xpending_range(self, name, groupname, min, max, count,
  1854. consumername=None):
  1855. """
  1856. Returns information about pending messages, in a range.
  1857. name: name of the stream.
  1858. groupname: name of the consumer group.
  1859. min: minimum stream ID.
  1860. max: maximum stream ID.
  1861. count: number of messages to return
  1862. consumername: name of a consumer to filter by (optional).
  1863. """
  1864. pieces = [name, groupname]
  1865. if min is not None or max is not None or count is not None:
  1866. if min is None or max is None or count is None:
  1867. raise DataError("XPENDING must be provided with min, max "
  1868. "and count parameters, or none of them. ")
  1869. if not isinstance(count, (int, long)) or count < -1:
  1870. raise DataError("XPENDING count must be a integer >= -1")
  1871. pieces.extend((min, max, str(count)))
  1872. if consumername is not None:
  1873. if min is None or max is None or count is None:
  1874. raise DataError("if XPENDING is provided with consumername,"
  1875. " it must be provided with min, max and"
  1876. " count parameters")
  1877. pieces.append(consumername)
  1878. return self.execute_command('XPENDING', *pieces, parse_detail=True)
  1879. def xrange(self, name, min='-', max='+', count=None):
  1880. """
  1881. Read stream values within an interval.
  1882. name: name of the stream.
  1883. start: first stream ID. defaults to '-',
  1884. meaning the earliest available.
  1885. finish: last stream ID. defaults to '+',
  1886. meaning the latest available.
  1887. count: if set, only return this many items, beginning with the
  1888. earliest available.
  1889. """
  1890. pieces = [min, max]
  1891. if count is not None:
  1892. if not isinstance(count, (int, long)) or count < 1:
  1893. raise DataError('XRANGE count must be a positive integer')
  1894. pieces.append(b'COUNT')
  1895. pieces.append(str(count))
  1896. return self.execute_command('XRANGE', name, *pieces)
  1897. def xread(self, streams, count=None, block=None):
  1898. """
  1899. Block and monitor multiple streams for new data.
  1900. streams: a dict of stream names to stream IDs, where
  1901. IDs indicate the last ID already seen.
  1902. count: if set, only return this many items, beginning with the
  1903. earliest available.
  1904. block: number of milliseconds to wait, if nothing already present.
  1905. """
  1906. pieces = []
  1907. if block is not None:
  1908. if not isinstance(block, (int, long)) or block < 0:
  1909. raise DataError('XREAD block must be a non-negative integer')
  1910. pieces.append(b'BLOCK')
  1911. pieces.append(str(block))
  1912. if count is not None:
  1913. if not isinstance(count, (int, long)) or count < 1:
  1914. raise DataError('XREAD count must be a positive integer')
  1915. pieces.append(b'COUNT')
  1916. pieces.append(str(count))
  1917. if not isinstance(streams, dict) or len(streams) == 0:
  1918. raise DataError('XREAD streams must be a non empty dict')
  1919. pieces.append(b'STREAMS')
  1920. keys, values = izip(*iteritems(streams))
  1921. pieces.extend(keys)
  1922. pieces.extend(values)
  1923. return self.execute_command('XREAD', *pieces)
  1924. def xreadgroup(self, groupname, consumername, streams, count=None,
  1925. block=None, noack=False):
  1926. """
  1927. Read from a stream via a consumer group.
  1928. groupname: name of the consumer group.
  1929. consumername: name of the requesting consumer.
  1930. streams: a dict of stream names to stream IDs, where
  1931. IDs indicate the last ID already seen.
  1932. count: if set, only return this many items, beginning with the
  1933. earliest available.
  1934. block: number of milliseconds to wait, if nothing already present.
  1935. noack: do not add messages to the PEL
  1936. """
  1937. pieces = [b'GROUP', groupname, consumername]
  1938. if count is not None:
  1939. if not isinstance(count, (int, long)) or count < 1:
  1940. raise DataError("XREADGROUP count must be a positive integer")
  1941. pieces.append(b'COUNT')
  1942. pieces.append(str(count))
  1943. if block is not None:
  1944. if not isinstance(block, (int, long)) or block < 0:
  1945. raise DataError("XREADGROUP block must be a non-negative "
  1946. "integer")
  1947. pieces.append(b'BLOCK')
  1948. pieces.append(str(block))
  1949. if noack:
  1950. pieces.append(b'NOACK')
  1951. if not isinstance(streams, dict) or len(streams) == 0:
  1952. raise DataError('XREADGROUP streams must be a non empty dict')
  1953. pieces.append(b'STREAMS')
  1954. pieces.extend(streams.keys())
  1955. pieces.extend(streams.values())
  1956. return self.execute_command('XREADGROUP', *pieces)
  1957. def xrevrange(self, name, max='+', min='-', count=None):
  1958. """
  1959. Read stream values within an interval, in reverse order.
  1960. name: name of the stream
  1961. start: first stream ID. defaults to '+',
  1962. meaning the latest available.
  1963. finish: last stream ID. defaults to '-',
  1964. meaning the earliest available.
  1965. count: if set, only return this many items, beginning with the
  1966. latest available.
  1967. """
  1968. pieces = [max, min]
  1969. if count is not None:
  1970. if not isinstance(count, (int, long)) or count < 1:
  1971. raise DataError('XREVRANGE count must be a positive integer')
  1972. pieces.append(b'COUNT')
  1973. pieces.append(str(count))
  1974. return self.execute_command('XREVRANGE', name, *pieces)
  1975. def xtrim(self, name, maxlen, approximate=True):
  1976. """
  1977. Trims old messages from a stream.
  1978. name: name of the stream.
  1979. maxlen: truncate old stream messages beyond this size
  1980. approximate: actual stream length may be slightly more than maxlen
  1981. """
  1982. pieces = [b'MAXLEN']
  1983. if approximate:
  1984. pieces.append(b'~')
  1985. pieces.append(maxlen)
  1986. return self.execute_command('XTRIM', name, *pieces)
  1987. # SORTED SET COMMANDS
  1988. def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False):
  1989. """
  1990. Set any number of element-name, score pairs to the key ``name``. Pairs
  1991. are specified as a dict of element-names keys to score values.
  1992. ``nx`` forces ZADD to only create new elements and not to update
  1993. scores for elements that already exist.
  1994. ``xx`` forces ZADD to only update scores of elements that already
  1995. exist. New elements will not be added.
  1996. ``ch`` modifies the return value to be the numbers of elements changed.
  1997. Changed elements include new elements that were added and elements
  1998. whose scores changed.
  1999. ``incr`` modifies ZADD to behave like ZINCRBY. In this mode only a
  2000. single element/score pair can be specified and the score is the amount
  2001. the existing score will be incremented by. When using this mode the
  2002. return value of ZADD will be the new score of the element.
  2003. The return value of ZADD varies based on the mode specified. With no
  2004. options, ZADD returns the number of new elements added to the sorted
  2005. set.
  2006. """
  2007. if not mapping:
  2008. raise DataError("ZADD requires at least one element/score pair")
  2009. if nx and xx:
  2010. raise DataError("ZADD allows either 'nx' or 'xx', not both")
  2011. if incr and len(mapping) != 1:
  2012. raise DataError("ZADD option 'incr' only works when passing a "
  2013. "single element/score pair")
  2014. pieces = []
  2015. options = {}
  2016. if nx:
  2017. pieces.append(b'NX')
  2018. if xx:
  2019. pieces.append(b'XX')
  2020. if ch:
  2021. pieces.append(b'CH')
  2022. if incr:
  2023. pieces.append(b'INCR')
  2024. options['as_score'] = True
  2025. for pair in iteritems(mapping):
  2026. pieces.append(pair[1])
  2027. pieces.append(pair[0])
  2028. return self.execute_command('ZADD', name, *pieces, **options)
  2029. def zcard(self, name):
  2030. "Return the number of elements in the sorted set ``name``"
  2031. return self.execute_command('ZCARD', name)
  2032. def zcount(self, name, min, max):
  2033. """
  2034. Returns the number of elements in the sorted set at key ``name`` with
  2035. a score between ``min`` and ``max``.
  2036. """
  2037. return self.execute_command('ZCOUNT', name, min, max)
  2038. def zincrby(self, name, amount, value):
  2039. "Increment the score of ``value`` in sorted set ``name`` by ``amount``"
  2040. return self.execute_command('ZINCRBY', name, amount, value)
  2041. def zinterstore(self, dest, keys, aggregate=None):
  2042. """
  2043. Intersect multiple sorted sets specified by ``keys`` into
  2044. a new sorted set, ``dest``. Scores in the destination will be
  2045. aggregated based on the ``aggregate``, or SUM if none is provided.
  2046. """
  2047. return self._zaggregate('ZINTERSTORE', dest, keys, aggregate)
  2048. def zlexcount(self, name, min, max):
  2049. """
  2050. Return the number of items in the sorted set ``name`` between the
  2051. lexicographical range ``min`` and ``max``.
  2052. """
  2053. return self.execute_command('ZLEXCOUNT', name, min, max)
  2054. def zpopmax(self, name, count=None):
  2055. """
  2056. Remove and return up to ``count`` members with the highest scores
  2057. from the sorted set ``name``.
  2058. """
  2059. args = (count is not None) and [count] or []
  2060. options = {
  2061. 'withscores': True
  2062. }
  2063. return self.execute_command('ZPOPMAX', name, *args, **options)
  2064. def zpopmin(self, name, count=None):
  2065. """
  2066. Remove and return up to ``count`` members with the lowest scores
  2067. from the sorted set ``name``.
  2068. """
  2069. args = (count is not None) and [count] or []
  2070. options = {
  2071. 'withscores': True
  2072. }
  2073. return self.execute_command('ZPOPMIN', name, *args, **options)
  2074. def bzpopmax(self, keys, timeout=0):
  2075. """
  2076. ZPOPMAX a value off of the first non-empty sorted set
  2077. named in the ``keys`` list.
  2078. If none of the sorted sets in ``keys`` has a value to ZPOPMAX,
  2079. then block for ``timeout`` seconds, or until a member gets added
  2080. to one of the sorted sets.
  2081. If timeout is 0, then block indefinitely.
  2082. """
  2083. if timeout is None:
  2084. timeout = 0
  2085. keys = list_or_args(keys, None)
  2086. keys.append(timeout)
  2087. return self.execute_command('BZPOPMAX', *keys)
  2088. def bzpopmin(self, keys, timeout=0):
  2089. """
  2090. ZPOPMIN a value off of the first non-empty sorted set
  2091. named in the ``keys`` list.
  2092. If none of the sorted sets in ``keys`` has a value to ZPOPMIN,
  2093. then block for ``timeout`` seconds, or until a member gets added
  2094. to one of the sorted sets.
  2095. If timeout is 0, then block indefinitely.
  2096. """
  2097. if timeout is None:
  2098. timeout = 0
  2099. keys = list_or_args(keys, None)
  2100. keys.append(timeout)
  2101. return self.execute_command('BZPOPMIN', *keys)
  2102. def zrange(self, name, start, end, desc=False, withscores=False,
  2103. score_cast_func=float):
  2104. """
  2105. Return a range of values from sorted set ``name`` between
  2106. ``start`` and ``end`` sorted in ascending order.
  2107. ``start`` and ``end`` can be negative, indicating the end of the range.
  2108. ``desc`` a boolean indicating whether to sort the results descendingly
  2109. ``withscores`` indicates to return the scores along with the values.
  2110. The return type is a list of (value, score) pairs
  2111. ``score_cast_func`` a callable used to cast the score return value
  2112. """
  2113. if desc:
  2114. return self.zrevrange(name, start, end, withscores,
  2115. score_cast_func)
  2116. pieces = ['ZRANGE', name, start, end]
  2117. if withscores:
  2118. pieces.append(b'WITHSCORES')
  2119. options = {
  2120. 'withscores': withscores,
  2121. 'score_cast_func': score_cast_func
  2122. }
  2123. return self.execute_command(*pieces, **options)
  2124. def zrangebylex(self, name, min, max, start=None, num=None):
  2125. """
  2126. Return the lexicographical range of values from sorted set ``name``
  2127. between ``min`` and ``max``.
  2128. If ``start`` and ``num`` are specified, then return a slice of the
  2129. range.
  2130. """
  2131. if (start is not None and num is None) or \
  2132. (num is not None and start is None):
  2133. raise DataError("``start`` and ``num`` must both be specified")
  2134. pieces = ['ZRANGEBYLEX', name, min, max]
  2135. if start is not None and num is not None:
  2136. pieces.extend([b'LIMIT', start, num])
  2137. return self.execute_command(*pieces)
  2138. def zrevrangebylex(self, name, max, min, start=None, num=None):
  2139. """
  2140. Return the reversed lexicographical range of values from sorted set
  2141. ``name`` between ``max`` and ``min``.
  2142. If ``start`` and ``num`` are specified, then return a slice of the
  2143. range.
  2144. """
  2145. if (start is not None and num is None) or \
  2146. (num is not None and start is None):
  2147. raise DataError("``start`` and ``num`` must both be specified")
  2148. pieces = ['ZREVRANGEBYLEX', name, max, min]
  2149. if start is not None and num is not None:
  2150. pieces.extend([b'LIMIT', start, num])
  2151. return self.execute_command(*pieces)
  2152. def zrangebyscore(self, name, min, max, start=None, num=None,
  2153. withscores=False, score_cast_func=float):
  2154. """
  2155. Return a range of values from the sorted set ``name`` with scores
  2156. between ``min`` and ``max``.
  2157. If ``start`` and ``num`` are specified, then return a slice
  2158. of the range.
  2159. ``withscores`` indicates to return the scores along with the values.
  2160. The return type is a list of (value, score) pairs
  2161. `score_cast_func`` a callable used to cast the score return value
  2162. """
  2163. if (start is not None and num is None) or \
  2164. (num is not None and start is None):
  2165. raise DataError("``start`` and ``num`` must both be specified")
  2166. pieces = ['ZRANGEBYSCORE', name, min, max]
  2167. if start is not None and num is not None:
  2168. pieces.extend([b'LIMIT', start, num])
  2169. if withscores:
  2170. pieces.append(b'WITHSCORES')
  2171. options = {
  2172. 'withscores': withscores,
  2173. 'score_cast_func': score_cast_func
  2174. }
  2175. return self.execute_command(*pieces, **options)
  2176. def zrank(self, name, value):
  2177. """
  2178. Returns a 0-based value indicating the rank of ``value`` in sorted set
  2179. ``name``
  2180. """
  2181. return self.execute_command('ZRANK', name, value)
  2182. def zrem(self, name, *values):
  2183. "Remove member ``values`` from sorted set ``name``"
  2184. return self.execute_command('ZREM', name, *values)
  2185. def zremrangebylex(self, name, min, max):
  2186. """
  2187. Remove all elements in the sorted set ``name`` between the
  2188. lexicographical range specified by ``min`` and ``max``.
  2189. Returns the number of elements removed.
  2190. """
  2191. return self.execute_command('ZREMRANGEBYLEX', name, min, max)
  2192. def zremrangebyrank(self, name, min, max):
  2193. """
  2194. Remove all elements in the sorted set ``name`` with ranks between
  2195. ``min`` and ``max``. Values are 0-based, ordered from smallest score
  2196. to largest. Values can be negative indicating the highest scores.
  2197. Returns the number of elements removed
  2198. """
  2199. return self.execute_command('ZREMRANGEBYRANK', name, min, max)
  2200. def zremrangebyscore(self, name, min, max):
  2201. """
  2202. Remove all elements in the sorted set ``name`` with scores
  2203. between ``min`` and ``max``. Returns the number of elements removed.
  2204. """
  2205. return self.execute_command('ZREMRANGEBYSCORE', name, min, max)
  2206. def zrevrange(self, name, start, end, withscores=False,
  2207. score_cast_func=float):
  2208. """
  2209. Return a range of values from sorted set ``name`` between
  2210. ``start`` and ``end`` sorted in descending order.
  2211. ``start`` and ``end`` can be negative, indicating the end of the range.
  2212. ``withscores`` indicates to return the scores along with the values
  2213. The return type is a list of (value, score) pairs
  2214. ``score_cast_func`` a callable used to cast the score return value
  2215. """
  2216. pieces = ['ZREVRANGE', name, start, end]
  2217. if withscores:
  2218. pieces.append(b'WITHSCORES')
  2219. options = {
  2220. 'withscores': withscores,
  2221. 'score_cast_func': score_cast_func
  2222. }
  2223. return self.execute_command(*pieces, **options)
  2224. def zrevrangebyscore(self, name, max, min, start=None, num=None,
  2225. withscores=False, score_cast_func=float):
  2226. """
  2227. Return a range of values from the sorted set ``name`` with scores
  2228. between ``min`` and ``max`` in descending order.
  2229. If ``start`` and ``num`` are specified, then return a slice
  2230. of the range.
  2231. ``withscores`` indicates to return the scores along with the values.
  2232. The return type is a list of (value, score) pairs
  2233. ``score_cast_func`` a callable used to cast the score return value
  2234. """
  2235. if (start is not None and num is None) or \
  2236. (num is not None and start is None):
  2237. raise DataError("``start`` and ``num`` must both be specified")
  2238. pieces = ['ZREVRANGEBYSCORE', name, max, min]
  2239. if start is not None and num is not None:
  2240. pieces.extend([b'LIMIT', start, num])
  2241. if withscores:
  2242. pieces.append(b'WITHSCORES')
  2243. options = {
  2244. 'withscores': withscores,
  2245. 'score_cast_func': score_cast_func
  2246. }
  2247. return self.execute_command(*pieces, **options)
  2248. def zrevrank(self, name, value):
  2249. """
  2250. Returns a 0-based value indicating the descending rank of
  2251. ``value`` in sorted set ``name``
  2252. """
  2253. return self.execute_command('ZREVRANK', name, value)
  2254. def zscore(self, name, value):
  2255. "Return the score of element ``value`` in sorted set ``name``"
  2256. return self.execute_command('ZSCORE', name, value)
  2257. def zunionstore(self, dest, keys, aggregate=None):
  2258. """
  2259. Union multiple sorted sets specified by ``keys`` into
  2260. a new sorted set, ``dest``. Scores in the destination will be
  2261. aggregated based on the ``aggregate``, or SUM if none is provided.
  2262. """
  2263. return self._zaggregate('ZUNIONSTORE', dest, keys, aggregate)
  2264. def _zaggregate(self, command, dest, keys, aggregate=None):
  2265. pieces = [command, dest, len(keys)]
  2266. if isinstance(keys, dict):
  2267. keys, weights = iterkeys(keys), itervalues(keys)
  2268. else:
  2269. weights = None
  2270. pieces.extend(keys)
  2271. if weights:
  2272. pieces.append(b'WEIGHTS')
  2273. pieces.extend(weights)
  2274. if aggregate:
  2275. pieces.append(b'AGGREGATE')
  2276. pieces.append(aggregate)
  2277. return self.execute_command(*pieces)
  2278. # HYPERLOGLOG COMMANDS
  2279. def pfadd(self, name, *values):
  2280. "Adds the specified elements to the specified HyperLogLog."
  2281. return self.execute_command('PFADD', name, *values)
  2282. def pfcount(self, *sources):
  2283. """
  2284. Return the approximated cardinality of
  2285. the set observed by the HyperLogLog at key(s).
  2286. """
  2287. return self.execute_command('PFCOUNT', *sources)
  2288. def pfmerge(self, dest, *sources):
  2289. "Merge N different HyperLogLogs into a single one."
  2290. return self.execute_command('PFMERGE', dest, *sources)
  2291. # HASH COMMANDS
  2292. def hdel(self, name, *keys):
  2293. "Delete ``keys`` from hash ``name``"
  2294. return self.execute_command('HDEL', name, *keys)
  2295. def hexists(self, name, key):
  2296. "Returns a boolean indicating if ``key`` exists within hash ``name``"
  2297. return self.execute_command('HEXISTS', name, key)
  2298. def hget(self, name, key):
  2299. "Return the value of ``key`` within the hash ``name``"
  2300. return self.execute_command('HGET', name, key)
  2301. def hgetall(self, name):
  2302. "Return a Python dict of the hash's name/value pairs"
  2303. return self.execute_command('HGETALL', name)
  2304. def hincrby(self, name, key, amount=1):
  2305. "Increment the value of ``key`` in hash ``name`` by ``amount``"
  2306. return self.execute_command('HINCRBY', name, key, amount)
  2307. def hincrbyfloat(self, name, key, amount=1.0):
  2308. """
  2309. Increment the value of ``key`` in hash ``name`` by floating ``amount``
  2310. """
  2311. return self.execute_command('HINCRBYFLOAT', name, key, amount)
  2312. def hkeys(self, name):
  2313. "Return the list of keys within hash ``name``"
  2314. return self.execute_command('HKEYS', name)
  2315. def hlen(self, name):
  2316. "Return the number of elements in hash ``name``"
  2317. return self.execute_command('HLEN', name)
  2318. def hset(self, name, key, value):
  2319. """
  2320. Set ``key`` to ``value`` within hash ``name``
  2321. Returns 1 if HSET created a new field, otherwise 0
  2322. """
  2323. return self.execute_command('HSET', name, key, value)
  2324. def hsetnx(self, name, key, value):
  2325. """
  2326. Set ``key`` to ``value`` within hash ``name`` if ``key`` does not
  2327. exist. Returns 1 if HSETNX created a field, otherwise 0.
  2328. """
  2329. return self.execute_command('HSETNX', name, key, value)
  2330. def hmset(self, name, mapping):
  2331. """
  2332. Set key to value within hash ``name`` for each corresponding
  2333. key and value from the ``mapping`` dict.
  2334. """
  2335. if not mapping:
  2336. raise DataError("'hmset' with 'mapping' of length 0")
  2337. items = []
  2338. for pair in iteritems(mapping):
  2339. items.extend(pair)
  2340. return self.execute_command('HMSET', name, *items)
  2341. def hmget(self, name, keys, *args):
  2342. "Returns a list of values ordered identically to ``keys``"
  2343. args = list_or_args(keys, args)
  2344. return self.execute_command('HMGET', name, *args)
  2345. def hvals(self, name):
  2346. "Return the list of values within hash ``name``"
  2347. return self.execute_command('HVALS', name)
  2348. def hstrlen(self, name, key):
  2349. """
  2350. Return the number of bytes stored in the value of ``key``
  2351. within hash ``name``
  2352. """
  2353. return self.execute_command('HSTRLEN', name, key)
  2354. def publish(self, channel, message):
  2355. """
  2356. Publish ``message`` on ``channel``.
  2357. Returns the number of subscribers the message was delivered to.
  2358. """
  2359. return self.execute_command('PUBLISH', channel, message)
  2360. def pubsub_channels(self, pattern='*'):
  2361. """
  2362. Return a list of channels that have at least one subscriber
  2363. """
  2364. return self.execute_command('PUBSUB CHANNELS', pattern)
  2365. def pubsub_numpat(self):
  2366. """
  2367. Returns the number of subscriptions to patterns
  2368. """
  2369. return self.execute_command('PUBSUB NUMPAT')
  2370. def pubsub_numsub(self, *args):
  2371. """
  2372. Return a list of (channel, number of subscribers) tuples
  2373. for each channel given in ``*args``
  2374. """
  2375. return self.execute_command('PUBSUB NUMSUB', *args)
  2376. def cluster(self, cluster_arg, *args):
  2377. return self.execute_command('CLUSTER %s' % cluster_arg.upper(), *args)
  2378. def eval(self, script, numkeys, *keys_and_args):
  2379. """
  2380. Execute the Lua ``script``, specifying the ``numkeys`` the script
  2381. will touch and the key names and argument values in ``keys_and_args``.
  2382. Returns the result of the script.
  2383. In practice, use the object returned by ``register_script``. This
  2384. function exists purely for Redis API completion.
  2385. """
  2386. return self.execute_command('EVAL', script, numkeys, *keys_and_args)
  2387. def evalsha(self, sha, numkeys, *keys_and_args):
  2388. """
  2389. Use the ``sha`` to execute a Lua script already registered via EVAL
  2390. or SCRIPT LOAD. Specify the ``numkeys`` the script will touch and the
  2391. key names and argument values in ``keys_and_args``. Returns the result
  2392. of the script.
  2393. In practice, use the object returned by ``register_script``. This
  2394. function exists purely for Redis API completion.
  2395. """
  2396. return self.execute_command('EVALSHA', sha, numkeys, *keys_and_args)
  2397. def script_exists(self, *args):
  2398. """
  2399. Check if a script exists in the script cache by specifying the SHAs of
  2400. each script as ``args``. Returns a list of boolean values indicating if
  2401. if each already script exists in the cache.
  2402. """
  2403. return self.execute_command('SCRIPT EXISTS', *args)
  2404. def script_flush(self):
  2405. "Flush all scripts from the script cache"
  2406. return self.execute_command('SCRIPT FLUSH')
  2407. def script_kill(self):
  2408. "Kill the currently executing Lua script"
  2409. return self.execute_command('SCRIPT KILL')
  2410. def script_load(self, script):
  2411. "Load a Lua ``script`` into the script cache. Returns the SHA."
  2412. return self.execute_command('SCRIPT LOAD', script)
  2413. def register_script(self, script):
  2414. """
  2415. Register a Lua ``script`` specifying the ``keys`` it will touch.
  2416. Returns a Script object that is callable and hides the complexity of
  2417. deal with scripts, keys, and shas. This is the preferred way to work
  2418. with Lua scripts.
  2419. """
  2420. return Script(self, script)
  2421. # GEO COMMANDS
  2422. def geoadd(self, name, *values):
  2423. """
  2424. Add the specified geospatial items to the specified key identified
  2425. by the ``name`` argument. The Geospatial items are given as ordered
  2426. members of the ``values`` argument, each item or place is formed by
  2427. the triad longitude, latitude and name.
  2428. """
  2429. if len(values) % 3 != 0:
  2430. raise DataError("GEOADD requires places with lon, lat and name"
  2431. " values")
  2432. return self.execute_command('GEOADD', name, *values)
  2433. def geodist(self, name, place1, place2, unit=None):
  2434. """
  2435. Return the distance between ``place1`` and ``place2`` members of the
  2436. ``name`` key.
  2437. The units must be one of the following : m, km mi, ft. By default
  2438. meters are used.
  2439. """
  2440. pieces = [name, place1, place2]
  2441. if unit and unit not in ('m', 'km', 'mi', 'ft'):
  2442. raise DataError("GEODIST invalid unit")
  2443. elif unit:
  2444. pieces.append(unit)
  2445. return self.execute_command('GEODIST', *pieces)
  2446. def geohash(self, name, *values):
  2447. """
  2448. Return the geo hash string for each item of ``values`` members of
  2449. the specified key identified by the ``name`` argument.
  2450. """
  2451. return self.execute_command('GEOHASH', name, *values)
  2452. def geopos(self, name, *values):
  2453. """
  2454. Return the positions of each item of ``values`` as members of
  2455. the specified key identified by the ``name`` argument. Each position
  2456. is represented by the pairs lon and lat.
  2457. """
  2458. return self.execute_command('GEOPOS', name, *values)
  2459. def georadius(self, name, longitude, latitude, radius, unit=None,
  2460. withdist=False, withcoord=False, withhash=False, count=None,
  2461. sort=None, store=None, store_dist=None):
  2462. """
  2463. Return the members of the specified key identified by the
  2464. ``name`` argument which are within the borders of the area specified
  2465. with the ``latitude`` and ``longitude`` location and the maximum
  2466. distance from the center specified by the ``radius`` value.
  2467. The units must be one of the following : m, km mi, ft. By default
  2468. ``withdist`` indicates to return the distances of each place.
  2469. ``withcoord`` indicates to return the latitude and longitude of
  2470. each place.
  2471. ``withhash`` indicates to return the geohash string of each place.
  2472. ``count`` indicates to return the number of elements up to N.
  2473. ``sort`` indicates to return the places in a sorted way, ASC for
  2474. nearest to fairest and DESC for fairest to nearest.
  2475. ``store`` indicates to save the places names in a sorted set named
  2476. with a specific key, each element of the destination sorted set is
  2477. populated with the score got from the original geo sorted set.
  2478. ``store_dist`` indicates to save the places names in a sorted set
  2479. named with a specific key, instead of ``store`` the sorted set
  2480. destination score is set with the distance.
  2481. """
  2482. return self._georadiusgeneric('GEORADIUS',
  2483. name, longitude, latitude, radius,
  2484. unit=unit, withdist=withdist,
  2485. withcoord=withcoord, withhash=withhash,
  2486. count=count, sort=sort, store=store,
  2487. store_dist=store_dist)
  2488. def georadiusbymember(self, name, member, radius, unit=None,
  2489. withdist=False, withcoord=False, withhash=False,
  2490. count=None, sort=None, store=None, store_dist=None):
  2491. """
  2492. This command is exactly like ``georadius`` with the sole difference
  2493. that instead of taking, as the center of the area to query, a longitude
  2494. and latitude value, it takes the name of a member already existing
  2495. inside the geospatial index represented by the sorted set.
  2496. """
  2497. return self._georadiusgeneric('GEORADIUSBYMEMBER',
  2498. name, member, radius, unit=unit,
  2499. withdist=withdist, withcoord=withcoord,
  2500. withhash=withhash, count=count,
  2501. sort=sort, store=store,
  2502. store_dist=store_dist)
  2503. def _georadiusgeneric(self, command, *args, **kwargs):
  2504. pieces = list(args)
  2505. if kwargs['unit'] and kwargs['unit'] not in ('m', 'km', 'mi', 'ft'):
  2506. raise DataError("GEORADIUS invalid unit")
  2507. elif kwargs['unit']:
  2508. pieces.append(kwargs['unit'])
  2509. else:
  2510. pieces.append('m',)
  2511. for arg_name, byte_repr in (
  2512. ('withdist', b'WITHDIST'),
  2513. ('withcoord', b'WITHCOORD'),
  2514. ('withhash', b'WITHHASH')):
  2515. if kwargs[arg_name]:
  2516. pieces.append(byte_repr)
  2517. if kwargs['count']:
  2518. pieces.extend([b'COUNT', kwargs['count']])
  2519. if kwargs['sort']:
  2520. if kwargs['sort'] == 'ASC':
  2521. pieces.append(b'ASC')
  2522. elif kwargs['sort'] == 'DESC':
  2523. pieces.append(b'DESC')
  2524. else:
  2525. raise DataError("GEORADIUS invalid sort")
  2526. if kwargs['store'] and kwargs['store_dist']:
  2527. raise DataError("GEORADIUS store and store_dist cant be set"
  2528. " together")
  2529. if kwargs['store']:
  2530. pieces.extend([b'STORE', kwargs['store']])
  2531. if kwargs['store_dist']:
  2532. pieces.extend([b'STOREDIST', kwargs['store_dist']])
  2533. return self.execute_command(command, *pieces, **kwargs)
  2534. StrictRedis = Redis
  2535. class Monitor(object):
  2536. """
  2537. Monitor is useful for handling the MONITOR command to the redis server.
  2538. next_command() method returns one command from monitor
  2539. listen() method yields commands from monitor.
  2540. """
  2541. monitor_re = re.compile(r'\[(\d+) (.*)\] (.*)')
  2542. command_re = re.compile(r'"(.*?)(?<!\\)"')
  2543. def __init__(self, connection_pool):
  2544. self.connection_pool = connection_pool
  2545. self.connection = self.connection_pool.get_connection('MONITOR')
  2546. def __enter__(self):
  2547. self.connection.send_command('MONITOR')
  2548. # check that monitor returns 'OK', but don't return it to user
  2549. response = self.connection.read_response()
  2550. if not bool_ok(response):
  2551. raise RedisError('MONITOR failed: %s' % response)
  2552. return self
  2553. def __exit__(self, *args):
  2554. self.connection.disconnect()
  2555. self.connection_pool.release(self.connection)
  2556. def next_command(self):
  2557. "Parse the response from a monitor command"
  2558. response = self.connection.read_response()
  2559. if isinstance(response, bytes):
  2560. response = self.connection.encoder.decode(response, force=True)
  2561. command_time, command_data = response.split(' ', 1)
  2562. m = self.monitor_re.match(command_data)
  2563. db_id, client_info, command = m.groups()
  2564. command = ' '.join(self.command_re.findall(command))
  2565. command = command.replace('\\"', '"').replace('\\\\', '\\')
  2566. if client_info == 'lua':
  2567. client_address = 'lua'
  2568. client_port = ''
  2569. client_type = 'lua'
  2570. elif client_info.startswith('unix'):
  2571. client_address = 'unix'
  2572. client_port = client_info[5:]
  2573. client_type = 'unix'
  2574. else:
  2575. # use rsplit as ipv6 addresses contain colons
  2576. client_address, client_port = client_info.rsplit(':', 1)
  2577. client_type = 'tcp'
  2578. return {
  2579. 'time': float(command_time),
  2580. 'db': int(db_id),
  2581. 'client_address': client_address,
  2582. 'client_port': client_port,
  2583. 'client_type': client_type,
  2584. 'command': command
  2585. }
  2586. def listen(self):
  2587. "Listen for commands coming to the server."
  2588. while True:
  2589. yield self.next_command()
  2590. class PubSub(object):
  2591. """
  2592. PubSub provides publish, subscribe and listen support to Redis channels.
  2593. After subscribing to one or more channels, the listen() method will block
  2594. until a message arrives on one of the subscribed channels. That message
  2595. will be returned and it's safe to start listening again.
  2596. """
  2597. PUBLISH_MESSAGE_TYPES = ('message', 'pmessage')
  2598. UNSUBSCRIBE_MESSAGE_TYPES = ('unsubscribe', 'punsubscribe')
  2599. HEALTH_CHECK_MESSAGE = 'redis-py-health-check'
  2600. def __init__(self, connection_pool, shard_hint=None,
  2601. ignore_subscribe_messages=False):
  2602. self.connection_pool = connection_pool
  2603. self.shard_hint = shard_hint
  2604. self.ignore_subscribe_messages = ignore_subscribe_messages
  2605. self.connection = None
  2606. # we need to know the encoding options for this connection in order
  2607. # to lookup channel and pattern names for callback handlers.
  2608. self.encoder = self.connection_pool.get_encoder()
  2609. if self.encoder.decode_responses:
  2610. self.health_check_response = ['pong', self.HEALTH_CHECK_MESSAGE]
  2611. else:
  2612. self.health_check_response = [
  2613. b'pong',
  2614. self.encoder.encode(self.HEALTH_CHECK_MESSAGE)
  2615. ]
  2616. self.reset()
  2617. def __del__(self):
  2618. try:
  2619. # if this object went out of scope prior to shutting down
  2620. # subscriptions, close the connection manually before
  2621. # returning it to the connection pool
  2622. self.reset()
  2623. except Exception:
  2624. pass
  2625. def reset(self):
  2626. if self.connection:
  2627. self.connection.disconnect()
  2628. self.connection.clear_connect_callbacks()
  2629. self.connection_pool.release(self.connection)
  2630. self.connection = None
  2631. self.channels = {}
  2632. self.pending_unsubscribe_channels = set()
  2633. self.patterns = {}
  2634. self.pending_unsubscribe_patterns = set()
  2635. def close(self):
  2636. self.reset()
  2637. def on_connect(self, connection):
  2638. "Re-subscribe to any channels and patterns previously subscribed to"
  2639. # NOTE: for python3, we can't pass bytestrings as keyword arguments
  2640. # so we need to decode channel/pattern names back to unicode strings
  2641. # before passing them to [p]subscribe.
  2642. self.pending_unsubscribe_channels.clear()
  2643. self.pending_unsubscribe_patterns.clear()
  2644. if self.channels:
  2645. channels = {}
  2646. for k, v in iteritems(self.channels):
  2647. channels[self.encoder.decode(k, force=True)] = v
  2648. self.subscribe(**channels)
  2649. if self.patterns:
  2650. patterns = {}
  2651. for k, v in iteritems(self.patterns):
  2652. patterns[self.encoder.decode(k, force=True)] = v
  2653. self.psubscribe(**patterns)
  2654. @property
  2655. def subscribed(self):
  2656. "Indicates if there are subscriptions to any channels or patterns"
  2657. return bool(self.channels or self.patterns)
  2658. def execute_command(self, *args):
  2659. "Execute a publish/subscribe command"
  2660. # NOTE: don't parse the response in this function -- it could pull a
  2661. # legitimate message off the stack if the connection is already
  2662. # subscribed to one or more channels
  2663. if self.connection is None:
  2664. self.connection = self.connection_pool.get_connection(
  2665. 'pubsub',
  2666. self.shard_hint
  2667. )
  2668. # register a callback that re-subscribes to any channels we
  2669. # were listening to when we were disconnected
  2670. self.connection.register_connect_callback(self.on_connect)
  2671. connection = self.connection
  2672. kwargs = {'check_health': not self.subscribed}
  2673. self._execute(connection, connection.send_command, *args, **kwargs)
  2674. def _execute(self, connection, command, *args, **kwargs):
  2675. try:
  2676. return command(*args, **kwargs)
  2677. except (ConnectionError, TimeoutError) as e:
  2678. connection.disconnect()
  2679. if not (connection.retry_on_timeout and
  2680. isinstance(e, TimeoutError)):
  2681. raise
  2682. # Connect manually here. If the Redis server is down, this will
  2683. # fail and raise a ConnectionError as desired.
  2684. connection.connect()
  2685. # the ``on_connect`` callback should haven been called by the
  2686. # connection to resubscribe us to any channels and patterns we were
  2687. # previously listening to
  2688. return command(*args, **kwargs)
  2689. def parse_response(self, block=True, timeout=0):
  2690. "Parse the response from a publish/subscribe command"
  2691. conn = self.connection
  2692. if conn is None:
  2693. raise RuntimeError(
  2694. 'pubsub connection not set: '
  2695. 'did you forget to call subscribe() or psubscribe()?')
  2696. self.check_health()
  2697. if not block and not conn.can_read(timeout=timeout):
  2698. return None
  2699. response = self._execute(conn, conn.read_response)
  2700. if conn.health_check_interval and \
  2701. response == self.health_check_response:
  2702. # ignore the health check message as user might not expect it
  2703. return None
  2704. return response
  2705. def check_health(self):
  2706. conn = self.connection
  2707. if conn is None:
  2708. raise RuntimeError(
  2709. 'pubsub connection not set: '
  2710. 'did you forget to call subscribe() or psubscribe()?')
  2711. if conn.health_check_interval and time.time() > conn.next_health_check:
  2712. conn.send_command('PING', self.HEALTH_CHECK_MESSAGE,
  2713. check_health=False)
  2714. def _normalize_keys(self, data):
  2715. """
  2716. normalize channel/pattern names to be either bytes or strings
  2717. based on whether responses are automatically decoded. this saves us
  2718. from coercing the value for each message coming in.
  2719. """
  2720. encode = self.encoder.encode
  2721. decode = self.encoder.decode
  2722. return {decode(encode(k)): v for k, v in iteritems(data)}
  2723. def psubscribe(self, *args, **kwargs):
  2724. """
  2725. Subscribe to channel patterns. Patterns supplied as keyword arguments
  2726. expect a pattern name as the key and a callable as the value. A
  2727. pattern's callable will be invoked automatically when a message is
  2728. received on that pattern rather than producing a message via
  2729. ``listen()``.
  2730. """
  2731. if args:
  2732. args = list_or_args(args[0], args[1:])
  2733. new_patterns = dict.fromkeys(args)
  2734. new_patterns.update(kwargs)
  2735. ret_val = self.execute_command('PSUBSCRIBE', *iterkeys(new_patterns))
  2736. # update the patterns dict AFTER we send the command. we don't want to
  2737. # subscribe twice to these patterns, once for the command and again
  2738. # for the reconnection.
  2739. new_patterns = self._normalize_keys(new_patterns)
  2740. self.patterns.update(new_patterns)
  2741. self.pending_unsubscribe_patterns.difference_update(new_patterns)
  2742. return ret_val
  2743. def punsubscribe(self, *args):
  2744. """
  2745. Unsubscribe from the supplied patterns. If empty, unsubscribe from
  2746. all patterns.
  2747. """
  2748. if args:
  2749. args = list_or_args(args[0], args[1:])
  2750. patterns = self._normalize_keys(dict.fromkeys(args))
  2751. else:
  2752. patterns = self.patterns
  2753. self.pending_unsubscribe_patterns.update(patterns)
  2754. return self.execute_command('PUNSUBSCRIBE', *args)
  2755. def subscribe(self, *args, **kwargs):
  2756. """
  2757. Subscribe to channels. Channels supplied as keyword arguments expect
  2758. a channel name as the key and a callable as the value. A channel's
  2759. callable will be invoked automatically when a message is received on
  2760. that channel rather than producing a message via ``listen()`` or
  2761. ``get_message()``.
  2762. """
  2763. if args:
  2764. args = list_or_args(args[0], args[1:])
  2765. new_channels = dict.fromkeys(args)
  2766. new_channels.update(kwargs)
  2767. ret_val = self.execute_command('SUBSCRIBE', *iterkeys(new_channels))
  2768. # update the channels dict AFTER we send the command. we don't want to
  2769. # subscribe twice to these channels, once for the command and again
  2770. # for the reconnection.
  2771. new_channels = self._normalize_keys(new_channels)
  2772. self.channels.update(new_channels)
  2773. self.pending_unsubscribe_channels.difference_update(new_channels)
  2774. return ret_val
  2775. def unsubscribe(self, *args):
  2776. """
  2777. Unsubscribe from the supplied channels. If empty, unsubscribe from
  2778. all channels
  2779. """
  2780. if args:
  2781. args = list_or_args(args[0], args[1:])
  2782. channels = self._normalize_keys(dict.fromkeys(args))
  2783. else:
  2784. channels = self.channels
  2785. self.pending_unsubscribe_channels.update(channels)
  2786. return self.execute_command('UNSUBSCRIBE', *args)
  2787. def listen(self):
  2788. "Listen for messages on channels this client has been subscribed to"
  2789. while self.subscribed:
  2790. response = self.handle_message(self.parse_response(block=True))
  2791. if response is not None:
  2792. yield response
  2793. def get_message(self, ignore_subscribe_messages=False, timeout=0):
  2794. """
  2795. Get the next message if one is available, otherwise None.
  2796. If timeout is specified, the system will wait for `timeout` seconds
  2797. before returning. Timeout should be specified as a floating point
  2798. number.
  2799. """
  2800. response = self.parse_response(block=False, timeout=timeout)
  2801. if response:
  2802. return self.handle_message(response, ignore_subscribe_messages)
  2803. return None
  2804. def ping(self, message=None):
  2805. """
  2806. Ping the Redis server
  2807. """
  2808. message = '' if message is None else message
  2809. return self.execute_command('PING', message)
  2810. def handle_message(self, response, ignore_subscribe_messages=False):
  2811. """
  2812. Parses a pub/sub message. If the channel or pattern was subscribed to
  2813. with a message handler, the handler is invoked instead of a parsed
  2814. message being returned.
  2815. """
  2816. message_type = nativestr(response[0])
  2817. if message_type == 'pmessage':
  2818. message = {
  2819. 'type': message_type,
  2820. 'pattern': response[1],
  2821. 'channel': response[2],
  2822. 'data': response[3]
  2823. }
  2824. elif message_type == 'pong':
  2825. message = {
  2826. 'type': message_type,
  2827. 'pattern': None,
  2828. 'channel': None,
  2829. 'data': response[1]
  2830. }
  2831. else:
  2832. message = {
  2833. 'type': message_type,
  2834. 'pattern': None,
  2835. 'channel': response[1],
  2836. 'data': response[2]
  2837. }
  2838. # if this is an unsubscribe message, remove it from memory
  2839. if message_type in self.UNSUBSCRIBE_MESSAGE_TYPES:
  2840. if message_type == 'punsubscribe':
  2841. pattern = response[1]
  2842. if pattern in self.pending_unsubscribe_patterns:
  2843. self.pending_unsubscribe_patterns.remove(pattern)
  2844. self.patterns.pop(pattern, None)
  2845. else:
  2846. channel = response[1]
  2847. if channel in self.pending_unsubscribe_channels:
  2848. self.pending_unsubscribe_channels.remove(channel)
  2849. self.channels.pop(channel, None)
  2850. if message_type in self.PUBLISH_MESSAGE_TYPES:
  2851. # if there's a message handler, invoke it
  2852. if message_type == 'pmessage':
  2853. handler = self.patterns.get(message['pattern'], None)
  2854. else:
  2855. handler = self.channels.get(message['channel'], None)
  2856. if handler:
  2857. handler(message)
  2858. return None
  2859. elif message_type != 'pong':
  2860. # this is a subscribe/unsubscribe message. ignore if we don't
  2861. # want them
  2862. if ignore_subscribe_messages or self.ignore_subscribe_messages:
  2863. return None
  2864. return message
  2865. def run_in_thread(self, sleep_time=0, daemon=False):
  2866. for channel, handler in iteritems(self.channels):
  2867. if handler is None:
  2868. raise PubSubError("Channel: '%s' has no handler registered" %
  2869. channel)
  2870. for pattern, handler in iteritems(self.patterns):
  2871. if handler is None:
  2872. raise PubSubError("Pattern: '%s' has no handler registered" %
  2873. pattern)
  2874. thread = PubSubWorkerThread(self, sleep_time, daemon=daemon)
  2875. thread.start()
  2876. return thread
  2877. class PubSubWorkerThread(threading.Thread):
  2878. def __init__(self, pubsub, sleep_time, daemon=False):
  2879. super(PubSubWorkerThread, self).__init__()
  2880. self.daemon = daemon
  2881. self.pubsub = pubsub
  2882. self.sleep_time = sleep_time
  2883. self._running = threading.Event()
  2884. def run(self):
  2885. if self._running.is_set():
  2886. return
  2887. self._running.set()
  2888. pubsub = self.pubsub
  2889. sleep_time = self.sleep_time
  2890. while self._running.is_set():
  2891. pubsub.get_message(ignore_subscribe_messages=True,
  2892. timeout=sleep_time)
  2893. pubsub.close()
  2894. def stop(self):
  2895. # trip the flag so the run loop exits. the run loop will
  2896. # close the pubsub connection, which disconnects the socket
  2897. # and returns the connection to the pool.
  2898. self._running.clear()
  2899. class Pipeline(Redis):
  2900. """
  2901. Pipelines provide a way to transmit multiple commands to the Redis server
  2902. in one transmission. This is convenient for batch processing, such as
  2903. saving all the values in a list to Redis.
  2904. All commands executed within a pipeline are wrapped with MULTI and EXEC
  2905. calls. This guarantees all commands executed in the pipeline will be
  2906. executed atomically.
  2907. Any command raising an exception does *not* halt the execution of
  2908. subsequent commands in the pipeline. Instead, the exception is caught
  2909. and its instance is placed into the response list returned by execute().
  2910. Code iterating over the response list should be able to deal with an
  2911. instance of an exception as a potential value. In general, these will be
  2912. ResponseError exceptions, such as those raised when issuing a command
  2913. on a key of a different datatype.
  2914. """
  2915. UNWATCH_COMMANDS = {'DISCARD', 'EXEC', 'UNWATCH'}
  2916. def __init__(self, connection_pool, response_callbacks, transaction,
  2917. shard_hint):
  2918. self.connection_pool = connection_pool
  2919. self.connection = None
  2920. self.response_callbacks = response_callbacks
  2921. self.transaction = transaction
  2922. self.shard_hint = shard_hint
  2923. self.watching = False
  2924. self.reset()
  2925. def __enter__(self):
  2926. return self
  2927. def __exit__(self, exc_type, exc_value, traceback):
  2928. self.reset()
  2929. def __del__(self):
  2930. try:
  2931. self.reset()
  2932. except Exception:
  2933. pass
  2934. def __len__(self):
  2935. return len(self.command_stack)
  2936. def reset(self):
  2937. self.command_stack = []
  2938. self.scripts = set()
  2939. # make sure to reset the connection state in the event that we were
  2940. # watching something
  2941. if self.watching and self.connection:
  2942. try:
  2943. # call this manually since our unwatch or
  2944. # immediate_execute_command methods can call reset()
  2945. self.connection.send_command('UNWATCH')
  2946. self.connection.read_response()
  2947. except ConnectionError:
  2948. # disconnect will also remove any previous WATCHes
  2949. self.connection.disconnect()
  2950. # clean up the other instance attributes
  2951. self.watching = False
  2952. self.explicit_transaction = False
  2953. # we can safely return the connection to the pool here since we're
  2954. # sure we're no longer WATCHing anything
  2955. if self.connection:
  2956. self.connection_pool.release(self.connection)
  2957. self.connection = None
  2958. def multi(self):
  2959. """
  2960. Start a transactional block of the pipeline after WATCH commands
  2961. are issued. End the transactional block with `execute`.
  2962. """
  2963. if self.explicit_transaction:
  2964. raise RedisError('Cannot issue nested calls to MULTI')
  2965. if self.command_stack:
  2966. raise RedisError('Commands without an initial WATCH have already '
  2967. 'been issued')
  2968. self.explicit_transaction = True
  2969. def execute_command(self, *args, **kwargs):
  2970. if (self.watching or args[0] == 'WATCH') and \
  2971. not self.explicit_transaction:
  2972. return self.immediate_execute_command(*args, **kwargs)
  2973. return self.pipeline_execute_command(*args, **kwargs)
  2974. def immediate_execute_command(self, *args, **options):
  2975. """
  2976. Execute a command immediately, but don't auto-retry on a
  2977. ConnectionError if we're already WATCHing a variable. Used when
  2978. issuing WATCH or subsequent commands retrieving their values but before
  2979. MULTI is called.
  2980. """
  2981. command_name = args[0]
  2982. conn = self.connection
  2983. # if this is the first call, we need a connection
  2984. if not conn:
  2985. conn = self.connection_pool.get_connection(command_name,
  2986. self.shard_hint)
  2987. self.connection = conn
  2988. try:
  2989. conn.send_command(*args)
  2990. return self.parse_response(conn, command_name, **options)
  2991. except (ConnectionError, TimeoutError) as e:
  2992. conn.disconnect()
  2993. # if we were already watching a variable, the watch is no longer
  2994. # valid since this connection has died. raise a WatchError, which
  2995. # indicates the user should retry this transaction.
  2996. if self.watching:
  2997. self.reset()
  2998. raise WatchError("A ConnectionError occured on while watching "
  2999. "one or more keys")
  3000. # if retry_on_timeout is not set, or the error is not
  3001. # a TimeoutError, raise it
  3002. if not (conn.retry_on_timeout and isinstance(e, TimeoutError)):
  3003. self.reset()
  3004. raise
  3005. # retry_on_timeout is set, this is a TimeoutError and we are not
  3006. # already WATCHing any variables. retry the command.
  3007. try:
  3008. conn.send_command(*args)
  3009. return self.parse_response(conn, command_name, **options)
  3010. except (ConnectionError, TimeoutError):
  3011. # a subsequent failure should simply be raised
  3012. self.reset()
  3013. raise
  3014. def pipeline_execute_command(self, *args, **options):
  3015. """
  3016. Stage a command to be executed when execute() is next called
  3017. Returns the current Pipeline object back so commands can be
  3018. chained together, such as:
  3019. pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
  3020. At some other point, you can then run: pipe.execute(),
  3021. which will execute all commands queued in the pipe.
  3022. """
  3023. self.command_stack.append((args, options))
  3024. return self
  3025. def _execute_transaction(self, connection, commands, raise_on_error):
  3026. cmds = chain([(('MULTI', ), {})], commands, [(('EXEC', ), {})])
  3027. all_cmds = connection.pack_commands([args for args, options in cmds
  3028. if EMPTY_RESPONSE not in options])
  3029. connection.send_packed_command(all_cmds)
  3030. errors = []
  3031. # parse off the response for MULTI
  3032. # NOTE: we need to handle ResponseErrors here and continue
  3033. # so that we read all the additional command messages from
  3034. # the socket
  3035. try:
  3036. self.parse_response(connection, '_')
  3037. except ResponseError:
  3038. errors.append((0, sys.exc_info()[1]))
  3039. # and all the other commands
  3040. for i, command in enumerate(commands):
  3041. if EMPTY_RESPONSE in command[1]:
  3042. errors.append((i, command[1][EMPTY_RESPONSE]))
  3043. else:
  3044. try:
  3045. self.parse_response(connection, '_')
  3046. except ResponseError:
  3047. ex = sys.exc_info()[1]
  3048. self.annotate_exception(ex, i + 1, command[0])
  3049. errors.append((i, ex))
  3050. # parse the EXEC.
  3051. try:
  3052. response = self.parse_response(connection, '_')
  3053. except ExecAbortError:
  3054. if self.explicit_transaction:
  3055. self.immediate_execute_command('DISCARD')
  3056. if errors:
  3057. raise errors[0][1]
  3058. raise sys.exc_info()[1]
  3059. if response is None:
  3060. raise WatchError("Watched variable changed.")
  3061. # put any parse errors into the response
  3062. for i, e in errors:
  3063. response.insert(i, e)
  3064. if len(response) != len(commands):
  3065. self.connection.disconnect()
  3066. raise ResponseError("Wrong number of response items from "
  3067. "pipeline execution")
  3068. # find any errors in the response and raise if necessary
  3069. if raise_on_error:
  3070. self.raise_first_error(commands, response)
  3071. # We have to run response callbacks manually
  3072. data = []
  3073. for r, cmd in izip(response, commands):
  3074. if not isinstance(r, Exception):
  3075. args, options = cmd
  3076. command_name = args[0]
  3077. if command_name in self.response_callbacks:
  3078. r = self.response_callbacks[command_name](r, **options)
  3079. data.append(r)
  3080. return data
  3081. def _execute_pipeline(self, connection, commands, raise_on_error):
  3082. # build up all commands into a single request to increase network perf
  3083. all_cmds = connection.pack_commands([args for args, _ in commands])
  3084. connection.send_packed_command(all_cmds)
  3085. response = []
  3086. for args, options in commands:
  3087. try:
  3088. response.append(
  3089. self.parse_response(connection, args[0], **options))
  3090. except ResponseError:
  3091. response.append(sys.exc_info()[1])
  3092. if raise_on_error:
  3093. self.raise_first_error(commands, response)
  3094. return response
  3095. def raise_first_error(self, commands, response):
  3096. for i, r in enumerate(response):
  3097. if isinstance(r, ResponseError):
  3098. self.annotate_exception(r, i + 1, commands[i][0])
  3099. raise r
  3100. def annotate_exception(self, exception, number, command):
  3101. cmd = ' '.join(imap(safe_unicode, command))
  3102. msg = 'Command # %d (%s) of pipeline caused error: %s' % (
  3103. number, cmd, safe_unicode(exception.args[0]))
  3104. exception.args = (msg,) + exception.args[1:]
  3105. def parse_response(self, connection, command_name, **options):
  3106. result = Redis.parse_response(
  3107. self, connection, command_name, **options)
  3108. if command_name in self.UNWATCH_COMMANDS:
  3109. self.watching = False
  3110. elif command_name == 'WATCH':
  3111. self.watching = True
  3112. return result
  3113. def load_scripts(self):
  3114. # make sure all scripts that are about to be run on this pipeline exist
  3115. scripts = list(self.scripts)
  3116. immediate = self.immediate_execute_command
  3117. shas = [s.sha for s in scripts]
  3118. # we can't use the normal script_* methods because they would just
  3119. # get buffered in the pipeline.
  3120. exists = immediate('SCRIPT EXISTS', *shas)
  3121. if not all(exists):
  3122. for s, exist in izip(scripts, exists):
  3123. if not exist:
  3124. s.sha = immediate('SCRIPT LOAD', s.script)
  3125. def execute(self, raise_on_error=True):
  3126. "Execute all the commands in the current pipeline"
  3127. stack = self.command_stack
  3128. if not stack:
  3129. return []
  3130. if self.scripts:
  3131. self.load_scripts()
  3132. if self.transaction or self.explicit_transaction:
  3133. execute = self._execute_transaction
  3134. else:
  3135. execute = self._execute_pipeline
  3136. conn = self.connection
  3137. if not conn:
  3138. conn = self.connection_pool.get_connection('MULTI',
  3139. self.shard_hint)
  3140. # assign to self.connection so reset() releases the connection
  3141. # back to the pool after we're done
  3142. self.connection = conn
  3143. try:
  3144. return execute(conn, stack, raise_on_error)
  3145. except (ConnectionError, TimeoutError) as e:
  3146. conn.disconnect()
  3147. # if we were watching a variable, the watch is no longer valid
  3148. # since this connection has died. raise a WatchError, which
  3149. # indicates the user should retry this transaction.
  3150. if self.watching:
  3151. raise WatchError("A ConnectionError occured on while watching "
  3152. "one or more keys")
  3153. # if retry_on_timeout is not set, or the error is not
  3154. # a TimeoutError, raise it
  3155. if not (conn.retry_on_timeout and isinstance(e, TimeoutError)):
  3156. raise
  3157. # retry a TimeoutError when retry_on_timeout is set
  3158. return execute(conn, stack, raise_on_error)
  3159. finally:
  3160. self.reset()
  3161. def watch(self, *names):
  3162. "Watches the values at keys ``names``"
  3163. if self.explicit_transaction:
  3164. raise RedisError('Cannot issue a WATCH after a MULTI')
  3165. return self.execute_command('WATCH', *names)
  3166. def unwatch(self):
  3167. "Unwatches all previously specified keys"
  3168. return self.watching and self.execute_command('UNWATCH') or True
  3169. class Script(object):
  3170. "An executable Lua script object returned by ``register_script``"
  3171. def __init__(self, registered_client, script):
  3172. self.registered_client = registered_client
  3173. self.script = script
  3174. # Precalculate and store the SHA1 hex digest of the script.
  3175. if isinstance(script, basestring):
  3176. # We need the encoding from the client in order to generate an
  3177. # accurate byte representation of the script
  3178. encoder = registered_client.connection_pool.get_encoder()
  3179. script = encoder.encode(script)
  3180. self.sha = hashlib.sha1(script).hexdigest()
  3181. def __call__(self, keys=[], args=[], client=None):
  3182. "Execute the script, passing any required ``args``"
  3183. if client is None:
  3184. client = self.registered_client
  3185. args = tuple(keys) + tuple(args)
  3186. # make sure the Redis server knows about the script
  3187. if isinstance(client, Pipeline):
  3188. # Make sure the pipeline can register the script before executing.
  3189. client.scripts.add(self)
  3190. try:
  3191. return client.evalsha(self.sha, len(keys), *args)
  3192. except NoScriptError:
  3193. # Maybe the client is pointed to a differnet server than the client
  3194. # that created this instance?
  3195. # Overwrite the sha just in case there was a discrepancy.
  3196. self.sha = client.script_load(self.script)
  3197. return client.evalsha(self.sha, len(keys), *args)
  3198. class BitFieldOperation(object):
  3199. """
  3200. Command builder for BITFIELD commands.
  3201. """
  3202. def __init__(self, client, key, default_overflow=None):
  3203. self.client = client
  3204. self.key = key
  3205. self._default_overflow = default_overflow
  3206. self.reset()
  3207. def reset(self):
  3208. """
  3209. Reset the state of the instance to when it was constructed
  3210. """
  3211. self.operations = []
  3212. self._last_overflow = 'WRAP'
  3213. self.overflow(self._default_overflow or self._last_overflow)
  3214. def overflow(self, overflow):
  3215. """
  3216. Update the overflow algorithm of successive INCRBY operations
  3217. :param overflow: Overflow algorithm, one of WRAP, SAT, FAIL. See the
  3218. Redis docs for descriptions of these algorithmsself.
  3219. :returns: a :py:class:`BitFieldOperation` instance.
  3220. """
  3221. overflow = overflow.upper()
  3222. if overflow != self._last_overflow:
  3223. self._last_overflow = overflow
  3224. self.operations.append(('OVERFLOW', overflow))
  3225. return self
  3226. def incrby(self, fmt, offset, increment, overflow=None):
  3227. """
  3228. Increment a bitfield by a given amount.
  3229. :param fmt: format-string for the bitfield being updated, e.g. 'u8'
  3230. for an unsigned 8-bit integer.
  3231. :param offset: offset (in number of bits). If prefixed with a
  3232. '#', this is an offset multiplier, e.g. given the arguments
  3233. fmt='u8', offset='#2', the offset will be 16.
  3234. :param int increment: value to increment the bitfield by.
  3235. :param str overflow: overflow algorithm. Defaults to WRAP, but other
  3236. acceptable values are SAT and FAIL. See the Redis docs for
  3237. descriptions of these algorithms.
  3238. :returns: a :py:class:`BitFieldOperation` instance.
  3239. """
  3240. if overflow is not None:
  3241. self.overflow(overflow)
  3242. self.operations.append(('INCRBY', fmt, offset, increment))
  3243. return self
  3244. def get(self, fmt, offset):
  3245. """
  3246. Get the value of a given bitfield.
  3247. :param fmt: format-string for the bitfield being read, e.g. 'u8' for
  3248. an unsigned 8-bit integer.
  3249. :param offset: offset (in number of bits). If prefixed with a
  3250. '#', this is an offset multiplier, e.g. given the arguments
  3251. fmt='u8', offset='#2', the offset will be 16.
  3252. :returns: a :py:class:`BitFieldOperation` instance.
  3253. """
  3254. self.operations.append(('GET', fmt, offset))
  3255. return self
  3256. def set(self, fmt, offset, value):
  3257. """
  3258. Set the value of a given bitfield.
  3259. :param fmt: format-string for the bitfield being read, e.g. 'u8' for
  3260. an unsigned 8-bit integer.
  3261. :param offset: offset (in number of bits). If prefixed with a
  3262. '#', this is an offset multiplier, e.g. given the arguments
  3263. fmt='u8', offset='#2', the offset will be 16.
  3264. :param int value: value to set at the given position.
  3265. :returns: a :py:class:`BitFieldOperation` instance.
  3266. """
  3267. self.operations.append(('SET', fmt, offset, value))
  3268. return self
  3269. @property
  3270. def command(self):
  3271. cmd = ['BITFIELD', self.key]
  3272. for ops in self.operations:
  3273. cmd.extend(ops)
  3274. return cmd
  3275. def execute(self):
  3276. """
  3277. Execute the operation(s) in a single BITFIELD command. The return value
  3278. is a list of values corresponding to each operation. If the client
  3279. used to create this instance was a pipeline, the list of values
  3280. will be present within the pipeline's execute.
  3281. """
  3282. command = self.command
  3283. self.reset()
  3284. return self.client.execute_command(*command)