DESCRIPTION.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. redis-py
  2. ========
  3. The Python interface to the Redis key-value store.
  4. .. image:: https://secure.travis-ci.org/andymccurdy/redis-py.png?branch=master
  5. :target: http://travis-ci.org/andymccurdy/redis-py
  6. Installation
  7. ------------
  8. redis-py requires a running Redis server. See `Redis's quickstart
  9. <http://redis.io/topics/quickstart>`_ for installation instructions.
  10. To install redis-py, simply:
  11. .. code-block:: bash
  12. $ sudo pip install redis
  13. or alternatively (you really should be using pip though):
  14. .. code-block:: bash
  15. $ sudo easy_install redis
  16. or from source:
  17. .. code-block:: bash
  18. $ sudo python setup.py install
  19. Getting Started
  20. ---------------
  21. .. code-block:: pycon
  22. >>> import redis
  23. >>> r = redis.StrictRedis(host='localhost', port=6379, db=0)
  24. >>> r.set('foo', 'bar')
  25. True
  26. >>> r.get('foo')
  27. 'bar'
  28. API Reference
  29. -------------
  30. The `official Redis command documentation <http://redis.io/commands>`_ does a
  31. great job of explaining each command in detail. redis-py exposes two client
  32. classes that implement these commands. The StrictRedis class attempts to adhere
  33. to the official command syntax. There are a few exceptions:
  34. * **SELECT**: Not implemented. See the explanation in the Thread Safety section
  35. below.
  36. * **DEL**: 'del' is a reserved keyword in the Python syntax. Therefore redis-py
  37. uses 'delete' instead.
  38. * **CONFIG GET|SET**: These are implemented separately as config_get or config_set.
  39. * **MULTI/EXEC**: These are implemented as part of the Pipeline class. The
  40. pipeline is wrapped with the MULTI and EXEC statements by default when it
  41. is executed, which can be disabled by specifying transaction=False.
  42. See more about Pipelines below.
  43. * **SUBSCRIBE/LISTEN**: Similar to pipelines, PubSub is implemented as a separate
  44. class as it places the underlying connection in a state where it can't
  45. execute non-pubsub commands. Calling the pubsub method from the Redis client
  46. will return a PubSub instance where you can subscribe to channels and listen
  47. for messages. You can only call PUBLISH from the Redis client (see
  48. `this comment on issue #151
  49. <https://github.com/andymccurdy/redis-py/issues/151#issuecomment-1545015>`_
  50. for details).
  51. * **SCAN/SSCAN/HSCAN/ZSCAN**: The \*SCAN commands are implemented as they
  52. exist in the Redis documentation. In addition, each command has an equivilant
  53. iterator method. These are purely for convenience so the user doesn't have
  54. to keep track of the cursor while iterating. Use the
  55. scan_iter/sscan_iter/hscan_iter/zscan_iter methods for this behavior.
  56. In addition to the changes above, the Redis class, a subclass of StrictRedis,
  57. overrides several other commands to provide backwards compatibility with older
  58. versions of redis-py:
  59. * **LREM**: Order of 'num' and 'value' arguments reversed such that 'num' can
  60. provide a default value of zero.
  61. * **ZADD**: Redis specifies the 'score' argument before 'value'. These were swapped
  62. accidentally when being implemented and not discovered until after people
  63. were already using it. The Redis class expects \*args in the form of:
  64. `name1, score1, name2, score2, ...`
  65. * **SETEX**: Order of 'time' and 'value' arguments reversed.
  66. More Detail
  67. -----------
  68. Connection Pools
  69. ^^^^^^^^^^^^^^^^
  70. Behind the scenes, redis-py uses a connection pool to manage connections to
  71. a Redis server. By default, each Redis instance you create will in turn create
  72. its own connection pool. You can override this behavior and use an existing
  73. connection pool by passing an already created connection pool instance to the
  74. connection_pool argument of the Redis class. You may choose to do this in order
  75. to implement client side sharding or have finer grain control of how
  76. connections are managed.
  77. .. code-block:: pycon
  78. >>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
  79. >>> r = redis.Redis(connection_pool=pool)
  80. Connections
  81. ^^^^^^^^^^^
  82. ConnectionPools manage a set of Connection instances. redis-py ships with two
  83. types of Connections. The default, Connection, is a normal TCP socket based
  84. connection. The UnixDomainSocketConnection allows for clients running on the
  85. same device as the server to connect via a unix domain socket. To use a
  86. UnixDomainSocketConnection connection, simply pass the unix_socket_path
  87. argument, which is a string to the unix domain socket file. Additionally, make
  88. sure the unixsocket parameter is defined in your redis.conf file. It's
  89. commented out by default.
  90. .. code-block:: pycon
  91. >>> r = redis.Redis(unix_socket_path='/tmp/redis.sock')
  92. You can create your own Connection subclasses as well. This may be useful if
  93. you want to control the socket behavior within an async framework. To
  94. instantiate a client class using your own connection, you need to create
  95. a connection pool, passing your class to the connection_class argument.
  96. Other keyword parameters you pass to the pool will be passed to the class
  97. specified during initialization.
  98. .. code-block:: pycon
  99. >>> pool = redis.ConnectionPool(connection_class=YourConnectionClass,
  100. your_arg='...', ...)
  101. Parsers
  102. ^^^^^^^
  103. Parser classes provide a way to control how responses from the Redis server
  104. are parsed. redis-py ships with two parser classes, the PythonParser and the
  105. HiredisParser. By default, redis-py will attempt to use the HiredisParser if
  106. you have the hiredis module installed and will fallback to the PythonParser
  107. otherwise.
  108. Hiredis is a C library maintained by the core Redis team. Pieter Noordhuis was
  109. kind enough to create Python bindings. Using Hiredis can provide up to a
  110. 10x speed improvement in parsing responses from the Redis server. The
  111. performance increase is most noticeable when retrieving many pieces of data,
  112. such as from LRANGE or SMEMBERS operations.
  113. Hiredis is available on PyPI, and can be installed via pip or easy_install
  114. just like redis-py.
  115. .. code-block:: bash
  116. $ pip install hiredis
  117. or
  118. .. code-block:: bash
  119. $ easy_install hiredis
  120. Response Callbacks
  121. ^^^^^^^^^^^^^^^^^^
  122. The client class uses a set of callbacks to cast Redis responses to the
  123. appropriate Python type. There are a number of these callbacks defined on
  124. the Redis client class in a dictionary called RESPONSE_CALLBACKS.
  125. Custom callbacks can be added on a per-instance basis using the
  126. set_response_callback method. This method accepts two arguments: a command
  127. name and the callback. Callbacks added in this manner are only valid on the
  128. instance the callback is added to. If you want to define or override a callback
  129. globally, you should make a subclass of the Redis client and add your callback
  130. to its REDIS_CALLBACKS class dictionary.
  131. Response callbacks take at least one parameter: the response from the Redis
  132. server. Keyword arguments may also be accepted in order to further control
  133. how to interpret the response. These keyword arguments are specified during the
  134. command's call to execute_command. The ZRANGE implementation demonstrates the
  135. use of response callback keyword arguments with its "withscores" argument.
  136. Thread Safety
  137. ^^^^^^^^^^^^^
  138. Redis client instances can safely be shared between threads. Internally,
  139. connection instances are only retrieved from the connection pool during
  140. command execution, and returned to the pool directly after. Command execution
  141. never modifies state on the client instance.
  142. However, there is one caveat: the Redis SELECT command. The SELECT command
  143. allows you to switch the database currently in use by the connection. That
  144. database remains selected until another is selected or until the connection is
  145. closed. This creates an issue in that connections could be returned to the pool
  146. that are connected to a different database.
  147. As a result, redis-py does not implement the SELECT command on client
  148. instances. If you use multiple Redis databases within the same application, you
  149. should create a separate client instance (and possibly a separate connection
  150. pool) for each database.
  151. It is not safe to pass PubSub or Pipeline objects between threads.
  152. Pipelines
  153. ^^^^^^^^^
  154. Pipelines are a subclass of the base Redis class that provide support for
  155. buffering multiple commands to the server in a single request. They can be used
  156. to dramatically increase the performance of groups of commands by reducing the
  157. number of back-and-forth TCP packets between the client and server.
  158. Pipelines are quite simple to use:
  159. .. code-block:: pycon
  160. >>> r = redis.Redis(...)
  161. >>> r.set('bing', 'baz')
  162. >>> # Use the pipeline() method to create a pipeline instance
  163. >>> pipe = r.pipeline()
  164. >>> # The following SET commands are buffered
  165. >>> pipe.set('foo', 'bar')
  166. >>> pipe.get('bing')
  167. >>> # the EXECUTE call sends all buffered commands to the server, returning
  168. >>> # a list of responses, one for each command.
  169. >>> pipe.execute()
  170. [True, 'baz']
  171. For ease of use, all commands being buffered into the pipeline return the
  172. pipeline object itself. Therefore calls can be chained like:
  173. .. code-block:: pycon
  174. >>> pipe.set('foo', 'bar').sadd('faz', 'baz').incr('auto_number').execute()
  175. [True, True, 6]
  176. In addition, pipelines can also ensure the buffered commands are executed
  177. atomically as a group. This happens by default. If you want to disable the
  178. atomic nature of a pipeline but still want to buffer commands, you can turn
  179. off transactions.
  180. .. code-block:: pycon
  181. >>> pipe = r.pipeline(transaction=False)
  182. A common issue occurs when requiring atomic transactions but needing to
  183. retrieve values in Redis prior for use within the transaction. For instance,
  184. let's assume that the INCR command didn't exist and we need to build an atomic
  185. version of INCR in Python.
  186. The completely naive implementation could GET the value, increment it in
  187. Python, and SET the new value back. However, this is not atomic because
  188. multiple clients could be doing this at the same time, each getting the same
  189. value from GET.
  190. Enter the WATCH command. WATCH provides the ability to monitor one or more keys
  191. prior to starting a transaction. If any of those keys change prior the
  192. execution of that transaction, the entire transaction will be canceled and a
  193. WatchError will be raised. To implement our own client-side INCR command, we
  194. could do something like this:
  195. .. code-block:: pycon
  196. >>> with r.pipeline() as pipe:
  197. ... while 1:
  198. ... try:
  199. ... # put a WATCH on the key that holds our sequence value
  200. ... pipe.watch('OUR-SEQUENCE-KEY')
  201. ... # after WATCHing, the pipeline is put into immediate execution
  202. ... # mode until we tell it to start buffering commands again.
  203. ... # this allows us to get the current value of our sequence
  204. ... current_value = pipe.get('OUR-SEQUENCE-KEY')
  205. ... next_value = int(current_value) + 1
  206. ... # now we can put the pipeline back into buffered mode with MULTI
  207. ... pipe.multi()
  208. ... pipe.set('OUR-SEQUENCE-KEY', next_value)
  209. ... # and finally, execute the pipeline (the set command)
  210. ... pipe.execute()
  211. ... # if a WatchError wasn't raised during execution, everything
  212. ... # we just did happened atomically.
  213. ... break
  214. ... except WatchError:
  215. ... # another client must have changed 'OUR-SEQUENCE-KEY' between
  216. ... # the time we started WATCHing it and the pipeline's execution.
  217. ... # our best bet is to just retry.
  218. ... continue
  219. Note that, because the Pipeline must bind to a single connection for the
  220. duration of a WATCH, care must be taken to ensure that the connection is
  221. returned to the connection pool by calling the reset() method. If the
  222. Pipeline is used as a context manager (as in the example above) reset()
  223. will be called automatically. Of course you can do this the manual way by
  224. explicity calling reset():
  225. .. code-block:: pycon
  226. >>> pipe = r.pipeline()
  227. >>> while 1:
  228. ... try:
  229. ... pipe.watch('OUR-SEQUENCE-KEY')
  230. ... ...
  231. ... pipe.execute()
  232. ... break
  233. ... except WatchError:
  234. ... continue
  235. ... finally:
  236. ... pipe.reset()
  237. A convenience method named "transaction" exists for handling all the
  238. boilerplate of handling and retrying watch errors. It takes a callable that
  239. should expect a single parameter, a pipeline object, and any number of keys to
  240. be WATCHed. Our client-side INCR command above can be written like this,
  241. which is much easier to read:
  242. .. code-block:: pycon
  243. >>> def client_side_incr(pipe):
  244. ... current_value = pipe.get('OUR-SEQUENCE-KEY')
  245. ... next_value = int(current_value) + 1
  246. ... pipe.multi()
  247. ... pipe.set('OUR-SEQUENCE-KEY', next_value)
  248. >>>
  249. >>> r.transaction(client_side_incr, 'OUR-SEQUENCE-KEY')
  250. [True]
  251. Publish / Subscribe
  252. ^^^^^^^^^^^^^^^^^^^
  253. redis-py includes a `PubSub` object that subscribes to channels and listens
  254. for new messages. Creating a `PubSub` object is easy.
  255. .. code-block:: pycon
  256. >>> r = redis.StrictRedis(...)
  257. >>> p = r.pubsub()
  258. Once a `PubSub` instance is created, channels and patterns can be subscribed
  259. to.
  260. .. code-block:: pycon
  261. >>> p.subscribe('my-first-channel', 'my-second-channel', ...)
  262. >>> p.psubscribe('my-*', ...)
  263. The `PubSub` instance is now subscribed to those channels/patterns. The
  264. subscription confirmations can be seen by reading messages from the `PubSub`
  265. instance.
  266. .. code-block:: pycon
  267. >>> p.get_message()
  268. {'pattern': None, 'type': 'subscribe', 'channel': 'my-second-channel', 'data': 1L}
  269. >>> p.get_message()
  270. {'pattern': None, 'type': 'subscribe', 'channel': 'my-first-channel', 'data': 2L}
  271. >>> p.get_message()
  272. {'pattern': None, 'type': 'psubscribe', 'channel': 'my-*', 'data': 3L}
  273. Every message read from a `PubSub` instance will be a dictionary with the
  274. following keys.
  275. * **type**: One of the following: 'subscribe', 'unsubscribe', 'psubscribe',
  276. 'punsubscribe', 'message', 'pmessage'
  277. * **channel**: The channel [un]subscribed to or the channel a message was
  278. published to
  279. * **pattern**: The pattern that matched a published message's channel. Will be
  280. `None` in all cases except for 'pmessage' types.
  281. * **data**: The message data. With [un]subscribe messages, this value will be
  282. the number of channels and patterns the connection is currently subscribed
  283. to. With [p]message messages, this value will be the actual published
  284. message.
  285. Let's send a message now.
  286. .. code-block:: pycon
  287. # the publish method returns the number matching channel and pattern
  288. # subscriptions. 'my-first-channel' matches both the 'my-first-channel'
  289. # subscription and the 'my-*' pattern subscription, so this message will
  290. # be delivered to 2 channels/patterns
  291. >>> r.publish('my-first-channel', 'some data')
  292. 2
  293. >>> p.get_message()
  294. {'channel': 'my-first-channel', 'data': 'some data', 'pattern': None, 'type': 'message'}
  295. >>> p.get_message()
  296. {'channel': 'my-first-channel', 'data': 'some data', 'pattern': 'my-*', 'type': 'pmessage'}
  297. Unsubscribing works just like subscribing. If no arguments are passed to
  298. [p]unsubscribe, all channels or patterns will be unsubscribed from.
  299. .. code-block:: pycon
  300. >>> p.unsubscribe()
  301. >>> p.punsubscribe('my-*')
  302. >>> p.get_message()
  303. {'channel': 'my-second-channel', 'data': 2L, 'pattern': None, 'type': 'unsubscribe'}
  304. >>> p.get_message()
  305. {'channel': 'my-first-channel', 'data': 1L, 'pattern': None, 'type': 'unsubscribe'}
  306. >>> p.get_message()
  307. {'channel': 'my-*', 'data': 0L, 'pattern': None, 'type': 'punsubscribe'}
  308. redis-py also allows you to register callback functions to handle published
  309. messages. Message handlers take a single argument, the message, which is a
  310. dictionary just like the examples above. To subscribe to a channel or pattern
  311. with a message handler, pass the channel or pattern name as a keyword argument
  312. with its value being the callback function.
  313. When a message is read on a channel or pattern with a message handler, the
  314. message dictionary is created and passed to the message handler. In this case,
  315. a `None` value is returned from get_message() since the message was already
  316. handled.
  317. .. code-block:: pycon
  318. >>> def my_handler(message):
  319. ... print 'MY HANDLER: ', message['data']
  320. >>> p.subscribe(**{'my-channel': my_handler})
  321. # read the subscribe confirmation message
  322. >>> p.get_message()
  323. {'pattern': None, 'type': 'subscribe', 'channel': 'my-channel', 'data': 1L}
  324. >>> r.publish('my-channel', 'awesome data')
  325. 1
  326. # for the message handler to work, we need tell the instance to read data.
  327. # this can be done in several ways (read more below). we'll just use
  328. # the familiar get_message() function for now
  329. >>> message = p.get_message()
  330. MY HANDLER: awesome data
  331. # note here that the my_handler callback printed the string above.
  332. # `message` is None because the message was handled by our handler.
  333. >>> print message
  334. None
  335. If your application is not interested in the (sometimes noisy)
  336. subscribe/unsubscribe confirmation messages, you can ignore them by passing
  337. `ignore_subscribe_messages=True` to `r.pubsub()`. This will cause all
  338. subscribe/unsubscribe messages to be read, but they won't bubble up to your
  339. application.
  340. .. code-block:: pycon
  341. >>> p = r.pubsub(ignore_subscribe_messages=True)
  342. >>> p.subscribe('my-channel')
  343. >>> p.get_message() # hides the subscribe message and returns None
  344. >>> r.publish('my-channel')
  345. 1
  346. >>> p.get_message()
  347. {'channel': 'my-channel', data': 'my data', 'pattern': None, 'type': 'message'}
  348. There are three different strategies for reading messages.
  349. The examples above have been using `pubsub.get_message()`. Behind the scenes,
  350. `get_message()` uses the system's 'select' module to quickly poll the
  351. connection's socket. If there's data available to be read, `get_message()` will
  352. read it, format the message and return it or pass it to a message handler. If
  353. there's no data to be read, `get_message()` will immediately return None. This
  354. makes it trivial to integrate into an existing event loop inside your
  355. application.
  356. .. code-block:: pycon
  357. >>> while True:
  358. >>> message = p.get_message()
  359. >>> if message:
  360. >>> # do something with the message
  361. >>> time.sleep(0.001) # be nice to the system :)
  362. Older versions of redis-py only read messages with `pubsub.listen()`. listen()
  363. is a generator that blocks until a message is available. If your application
  364. doesn't need to do anything else but receive and act on messages received from
  365. redis, listen() is an easy way to get up an running.
  366. .. code-block:: pycon
  367. >>> for message in p.listen():
  368. ... # do something with the message
  369. The third option runs an event loop in a separate thread.
  370. `pubsub.run_in_thread()` creates a new thread and starts the event loop. The
  371. thread object is returned to the caller of `run_in_thread()`. The caller can
  372. use the `thread.stop()` method to shut down the event loop and thread. Behind
  373. the scenes, this is simply a wrapper around `get_message()` that runs in a
  374. separate thread, essentially creating a tiny non-blocking event loop for you.
  375. `run_in_thread()` takes an optional `sleep_time` argument. If specified, the
  376. event loop will call `time.sleep()` with the value in each iteration of the
  377. loop.
  378. Note: Since we're running in a separate thread, there's no way to handle
  379. messages that aren't automatically handled with registered message handlers.
  380. Therefore, redis-py prevents you from calling `run_in_thread()` if you're
  381. subscribed to patterns or channels that don't have message handlers attached.
  382. .. code-block:: pycon
  383. >>> p.subscribe(**{'my-channel': my_handler})
  384. >>> thread = p.run_in_thread(sleep_time=0.001)
  385. # the event loop is now running in the background processing messages
  386. # when it's time to shut it down...
  387. >>> thread.stop()
  388. A PubSub object adheres to the same encoding semantics as the client instance
  389. it was created from. Any channel or pattern that's unicode will be encoded
  390. using the `charset` specified on the client before being sent to Redis. If the
  391. client's `decode_responses` flag is set the False (the default), the
  392. 'channel', 'pattern' and 'data' values in message dictionaries will be byte
  393. strings (str on Python 2, bytes on Python 3). If the client's
  394. `decode_responses` is True, then the 'channel', 'pattern' and 'data' values
  395. will be automatically decoded to unicode strings using the client's `charset`.
  396. PubSub objects remember what channels and patterns they are subscribed to. In
  397. the event of a disconnection such as a network error or timeout, the
  398. PubSub object will re-subscribe to all prior channels and patterns when
  399. reconnecting. Messages that were published while the client was disconnected
  400. cannot be delivered. When you're finished with a PubSub object, call its
  401. `.close()` method to shutdown the connection.
  402. .. code-block:: pycon
  403. >>> p = r.pubsub()
  404. >>> ...
  405. >>> p.close()
  406. LUA Scripting
  407. ^^^^^^^^^^^^^
  408. redis-py supports the EVAL, EVALSHA, and SCRIPT commands. However, there are
  409. a number of edge cases that make these commands tedious to use in real world
  410. scenarios. Therefore, redis-py exposes a Script object that makes scripting
  411. much easier to use.
  412. To create a Script instance, use the `register_script` function on a client
  413. instance passing the LUA code as the first argument. `register_script` returns
  414. a Script instance that you can use throughout your code.
  415. The following trivial LUA script accepts two parameters: the name of a key and
  416. a multiplier value. The script fetches the value stored in the key, multiplies
  417. it with the multiplier value and returns the result.
  418. .. code-block:: pycon
  419. >>> r = redis.StrictRedis()
  420. >>> lua = """
  421. ... local value = redis.call('GET', KEYS[1])
  422. ... value = tonumber(value)
  423. ... return value * ARGV[1]"""
  424. >>> multiply = r.register_script(lua)
  425. `multiply` is now a Script instance that is invoked by calling it like a
  426. function. Script instances accept the following optional arguments:
  427. * **keys**: A list of key names that the script will access. This becomes the
  428. KEYS list in LUA.
  429. * **args**: A list of argument values. This becomes the ARGV list in LUA.
  430. * **client**: A redis-py Client or Pipeline instance that will invoke the
  431. script. If client isn't specified, the client that intiially
  432. created the Script instance (the one that `register_script` was
  433. invoked from) will be used.
  434. Continuing the example from above:
  435. .. code-block:: pycon
  436. >>> r.set('foo', 2)
  437. >>> multiply(keys=['foo'], args=[5])
  438. 10
  439. The value of key 'foo' is set to 2. When multiply is invoked, the 'foo' key is
  440. passed to the script along with the multiplier value of 5. LUA executes the
  441. script and returns the result, 10.
  442. Script instances can be executed using a different client instance, even one
  443. that points to a completely different Redis server.
  444. .. code-block:: pycon
  445. >>> r2 = redis.StrictRedis('redis2.example.com')
  446. >>> r2.set('foo', 3)
  447. >>> multiply(keys=['foo'], args=[5], client=r2)
  448. 15
  449. The Script object ensures that the LUA script is loaded into Redis's script
  450. cache. In the event of a NOSCRIPT error, it will load the script and retry
  451. executing it.
  452. Script objects can also be used in pipelines. The pipeline instance should be
  453. passed as the client argument when calling the script. Care is taken to ensure
  454. that the script is registered in Redis's script cache just prior to pipeline
  455. execution.
  456. .. code-block:: pycon
  457. >>> pipe = r.pipeline()
  458. >>> pipe.set('foo', 5)
  459. >>> multiply(keys=['foo'], args=[5], client=pipe)
  460. >>> pipe.execute()
  461. [True, 25]
  462. Sentinel support
  463. ^^^^^^^^^^^^^^^^
  464. redis-py can be used together with `Redis Sentinel <http://redis.io/topics/sentinel>`_
  465. to discover Redis nodes. You need to have at least one Sentinel daemon running
  466. in order to use redis-py's Sentinel support.
  467. Connecting redis-py to the Sentinel instance(s) is easy. You can use a
  468. Sentinel connection to discover the master and slaves network addresses:
  469. .. code-block:: pycon
  470. >>> from redis.sentinel import Sentinel
  471. >>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
  472. >>> sentinel.discover_master('mymaster')
  473. ('127.0.0.1', 6379)
  474. >>> sentinel.discover_slaves('mymaster')
  475. [('127.0.0.1', 6380)]
  476. You can also create Redis client connections from a Sentinel instance. You can
  477. connect to either the master (for write operations) or a slave (for read-only
  478. operations).
  479. .. code-block:: pycon
  480. >>> master = sentinel.master_for('mymaster', socket_timeout=0.1)
  481. >>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1)
  482. >>> master.set('foo', 'bar')
  483. >>> slave.get('foo')
  484. 'bar'
  485. The master and slave objects are normal StrictRedis instances with their
  486. connection pool bound to the Sentinel instance. When a Sentinel backed client
  487. attempts to establish a connection, it first queries the Sentinel servers to
  488. determine an appropriate host to connect to. If no server is found,
  489. a MasterNotFoundError or SlaveNotFoundError is raised. Both exceptions are
  490. subclasses of ConnectionError.
  491. When trying to connect to a slave client, the Sentinel connection pool will
  492. iterate over the list of slaves until it finds one that can be connected to.
  493. If no slaves can be connected to, a connection will be established with the
  494. master.
  495. See `Guidelines for Redis clients with support for Redis Sentinel
  496. <http://redis.io/topics/sentinel-clients>`_ to learn more about Redis Sentinel.
  497. Scan Iterators
  498. ^^^^^^^^^^^^^^
  499. The \*SCAN commands introduced in Redis 2.8 can be cumbersome to use. While
  500. these commands are fully supported, redis-py also exposes the following methods
  501. that return Python iterators for convenience: `scan_iter`, `hscan_iter`,
  502. `sscan_iter` and `zscan_iter`.
  503. .. code-block:: pycon
  504. >>> for key, value in (('A', '1'), ('B', '2'), ('C', '3')):
  505. ... r.set(key, value)
  506. >>> for key in r.scan_iter():
  507. ... print key, r.get(key)
  508. A 1
  509. B 2
  510. C 3
  511. Author
  512. ^^^^^^
  513. redis-py is developed and maintained by Andy McCurdy (sedrik@gmail.com).
  514. It can be found here: http://github.com/andymccurdy/redis-py
  515. Special thanks to:
  516. * Ludovico Magnocavallo, author of the original Python Redis client, from
  517. which some of the socket code is still used.
  518. * Alexander Solovyov for ideas on the generic response callback system.
  519. * Paul Hubbard for initial packaging support.