METADATA 27 KB

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