Python client for Redis 官翻文档2.10.1

github地址:https://github.com/andymccurdy/redis-py/
安装:
虽然称redis的python客户端称为redis-py,实际安装时的名字是redis.
redis-py运行需要先安装和运行起来redis-server的,具体看点击这个网站查看详细信息http://redis.io/topics/quickstart

几种安装方式:
pip安装
$ sudo pip install redis
easy_install安装
$ sudo easy_install redis
源码安装,先去https://pypi.python.org/pypi/redis这里下载安装包,进入setup.py的目录执行下面命令
$ sudo python setup.py install
NOTE:不建议Windows平台使用redis的

快速入门:
>>> import redis
>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')'bar'

API接口:
官方redis 命令文档非常伟大为我们做个每个命令的详细解释,你可以去redis官网查看。
redis-py 模块通过两个类(StrictRedis,Redis)来遵循官方的所有标准命令,不过下面的命令除外:
----SELECT:未实现,你会在下面的线程安全章节看到关于这个的解释
----DEL:del 在python中是关键字,所以在redis-py中用delete来代替
----CONFIG GET|SET:分别用config_get 和 config_set来代替
----MULTI/EXEC:事物命令是作为Pipeline类的一部分来实现的,Pipeline类是对事物命令的包装,你也可以通过参数transaction=False来控制事物的使用。在下面的  管道(Pipeline)部分有更详细的解释。
----SUBSCRIBE/LISTEN:类似于管道,发布定阅在class PubSub类中实现,从Redis客户端调用pubsub方法将返回一个pubsub实例,您可以订阅通道和侦听消息.你只能从客户机端调用发布(https://github.com/andymccurdy/redis-py/issues/151#issuecomment-1545015  请看这个注意事项 )
----SCAN/SSCAN/HSCAN/ZSCAN: *scan命令正如在redis命令文档中那样都被实现,此外,每个相对应scan命令都有一个迭代器的方法 scan_iter/sscan_iter/hscan_iter/zscan_iter

除了上面的变化外,Redis 类是 StrictRedis的子类, 为了提供向后的兼容性重写了一些方法:
    LREM: 调换num和value的顺序,这样num可以提供一个默认值为0
    ZADD: redis默认指定score参数 在 value的前面,但是redis-py里的Redis类期望是 name1, score1, name2, score2, ...这种形式,也是位置被变换了。
    SETEX: 调换 time  和value 参数顺序

连接池:
在幕后,redis-py 使用连接池管理连接到redis-server的连接.默认, 一旦你创建了一个Redis的实例 ,这个实例相应有自己的连接池。你可以重写此行为,在创建一个Redis实例的时候指定一个创建的连接池,告诉这个实例是使用哪个连接。(我的理解:如果存在多个redis-server,指定连接哪个)
>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
>>> r = redis.Redis(connection_pool=pool)

连接:
ConnectionPoll管理一组连接,redis-py提供两种方式连接到redis-server.
一种是(也是默认的)TCP 套接字类型
另一种是使用 UnixDomainSocket连接。通过传递unix_socket_path参数,这是一个字符串,代表unix domain socket
文件。 另外确保在redis.conf定义unixsocket,默认是注释掉的。(这个俺不懂,接触的少)

>>> r = redis.Redis(unix_socket_path='/tmp/redis.sock')

您可以创建自己的连接子类。如果你想控制套接字的行为在一个异步框架将会非常有用。
实例化一个客户端类使用你自己的连接,您需要创建一个连接池,通过你的connection_class类,还有相应的参数

>>> pool = redis.ConnectionPool(connection_class=YourConnectionClass,  
                             your_arg='...', ...)

解析器
Parser classes provide a way to control how responses from the Redis server are parsed. redis-py ships with two parser classes, the PythonParser and the HiredisParser. By default, redis-py will attempt to use the HiredisParser if you have the hiredis module installed and will fallback to the PythonParser otherwise.
解析器类提供了怎么样解析从Redis-server服务器返回的数据。
redis-py提供了两种解析器类,PythonParser 和 HiredisParser。默认使用HiredisParser,如果没有安装这个第三方模块就会使用PythonParser。(内部会尝试倒入HiredisParser,失败了就使用默认的)

Hiredis is a C library maintained by the core Redis team. Pieter Noordhuis was kind enough to create Python bindings. Using Hiredis can provide up to a 10x speed improvement in parsing responses from the Redis server. The performance increase is most noticeable when retrieving many pieces of data, such as from LRANGE or SMEMBERS operations.
Hiredis就是用C写,而且是redis核心组成员写的,速度是另一个的10倍,(这么严重)当检索大量数据时性能提升最为明显  如这几个LRANGE or SMEMBERS

Hiredis is available on PyPI, and can be installed via pip or easy_install just like redis-py.
$ pip install hiredis
or
$ easy_install hiredis

响应回调
The client class uses a set of callbacks to cast Redis responses to the appropriate Python type. There are a number of these callbacks defined on the Redis client class in a dictionary called RESPONSE_CALLBACKS.
客户端类用一组回调函数处理Redis返回的数据,同时转换成合适的python的类型。在Redis客户端类中定义了很多这种回调函数。(实际是放在StrictRedis类中,放在RESPONSE_CALLBACKS中,这是个字典)

Custom callbacks can be added on a per-instance basis using the set_response_callback method. This method accepts two arguments: a command name and the callback. Callbacks added in this manner are only valid on the instance the callback is added to. If you want to define or override a callback globally, you should make a subclass of the Redis client and add your callback to its REDIS_CALLBACKS class dictionary.
可以使用每个实例的set_response_callback方法添加自定义回调函数。回调函数接受两个参数:redis的命令和回调函数名。

def set_response_callback(self, command, callback):
        "Set a custom Response Callback"
        self.response_callbacks[command] = callback

如果你想定义一个新的回调或复写存在的回调函数,需要写一个Redis client继承原来的Redis client,添加你的回调放到REDIS_CALLBACKS中。
Response callbacks take at least one parameter: the response from the Redis server. Keyword arguments may also be accepted in order to further control how to interpret the response. These keyword arguments are specified during the command's call to execute_command. The ZRANGE implementation demonstrates the use of response callback keyword arguments with its "withscores" argument.

线程安全
Redis client instances can safely be shared between threads. Internally, connection instances are only retrieved from the connection pool during command execution, and returned to the pool directly after. Command execution never modifies state on the client instance.
redis客户端实例在现成之间安全共享。在内部,执行命令时从连接池中取出一个连接,使用完后再放回连接池。在客户端实例,命令执行不会修改状态.

However, there is one caveat: the Redis SELECT command. The SELECT command allows you to switch the database currently in use by the connection. That database remains selected until another is selected or until the connection is closed. This creates an issue in that connections could be returned to the pool that are connected to a different database.
但是有一个警告:Redis的select命令。select命令允许你从0号数据库切换到1号数据库使用当前的连接。0号数据库会被当前连接仍然选择直到其他连接选择它,或者当前的连接关闭。这就产生了一个问题,This creates an issue in that connections could be returned to the pool that are connected to a different database.

As a result, redis-py does not implement the SELECT command on client instances. If you use multiple Redis databases within the same application, you should create a separate client instance (and possibly a separate connection pool) for each database.
所以,redis-py没有实现select的命令。要是想在一个web应用程序中使用多个redis的数据库,应该创建一个单独的redis客户端为每个数据库(可能是一个单独的连接池)
red0 = redis.StrictRedis(
            host='localhost', port=6379,
            db=0, password=None, #用的是0号数据库
             charset='utf-8'
        )
red1 = redis.StrictRedis(
            host='localhost', port=6379,
            db=1, password=None,#用的是1号数据库
            charset='utf-8'
        )
It is not safe to pass PubSub or Pipeline objects between threads.
在线程之间传递PubSub 和 Pipeline是不安全的。