python 操作 redis

由官方文档而得
python 利用 redis 第三方库
首先安装
pip install redis
然后就可以开始愉快地使用了

import redis
r = redis.StricRedis(host='localhost', port=6379, db=0)
r.set('test', '1')
r.get('test')   # ->> '1'

注,r 方法一览:


dir(r)

dir(r)

默认情况下,响应以 Python3 的字节Python 2 的 str 形式返回,用户负责解码操作。
redis-py 实现了两个类来操作 redis

  1. StricRedis 尽量坚持官方语法,除了以下命令:
    • select 没有实现,考虑到了线程安全
    • del Python 关键字,用 delete 代替
    • config get|se 作为 config_get / config_set 实现
    • multi / exec 作为 Pipeline 类的一部分实现的。
  2. Redis 类是 StricRedis 的子类,提供向后的兼容性。推荐使用 StricRedis。Redis 覆盖了几个命令:
    • lrem num 和 value 参数顺序颠倒,num 提供默认值 0
    • zadd Redis类期望* args的形式为:name1,score1,name2,score2,...,而 StricRedis 是 score1,name1,score2,name2,...,这与 Redis 一样。
    • setex time 和 value 顺序颠倒。在 Redis 类中是:setex(key, value, time),在 StricRedis 类中是:setex(key, time, value)

连接池来操作

pool = redis.ConnectionPool(host = ' localhost ',port = 6379,db = 0)
r = redis.Redis(connection_pool = pool)

解析器

可以使用 Redis 官方维护的一个 C 库 hiredis
pip install hiredis

线程安全

可以在线程之间安全地共享 Redis 客户端实例。有一点需要注意:Redis SELECT命令。SELECT命令允许您切换连接当前使用的数据库。该数据库保持选定状态直到选择另一个数据库或连接关闭。这会产生一个问题,即连接可以返回到连接到不同数据库的池。因此不会实现 select 命令。
在线程之间传递PubSub或Pipeline对象是不安全的。

管道

一般用来执行事务操作

>>> r = redis.Redis(...)
>>> r.set('bing', 'baz')
>>> # Use the pipeline() method to create a pipeline instance
>>> pipe = r.pipeline()
>>> # The following SET commands are buffered
>>> pipe.set('foo', 'bar')
>>> pipe.get('bing')
>>> # the EXECUTE call sends all buffered commands to the server, returning
>>> # a list of responses, one for each command.
>>> pipe.execute()
[True, 'baz']

也可以进行链式操作

>>> pipe.set(' foo ',' bar ').sadd(' faz ',' baz ').incr(' auto_number ')。execute()
[True,True,6]

禁用原子性:
pipe = r.pipeline(transaction = False)
WATCH 监控命令:

>>> with r.pipeline() as pipe:
...     while 1:
...         try:
...            # 设置一个 watch
...             pipe.watch('OUR-SEQUENCE-KEY')
...             current_value = pipe.get('OUR-SEQUENCE-KEY')
...             next_value = int(current_value) + 1
...             # 开始事务
...             pipe.multi()
...             pipe.set('OUR-SEQUENCE-KEY', next_value)
...             # 执行
...             pipe.execute()
...             # 如果抛出 WatchError ,表示原子性失败
...             break
...        except WatchError:
...             # 另一个客户端修改了,我们必须重试
...             continue

由于 Pipeline 在 watch 期间绑定到单个连接,必须调用 reset() 来确保返回连接池,使用 with 上下文的话,它会自动调用。当然也可以手动调用:

>>> pipe = r.pipeline()
>>> while 1:
...     try:
...         pipe.watch('OUR-SEQUENCE-KEY')
...         ...
...         pipe.execute()
...         break
...     except WatchError:
...         continue
...     finally:
...         pipe.reset()

也可以使用 transaction() 方法来简化操作

>>> def client_side_incr(pipe):
...     current_value = pipe.get('OUR-SEQUENCE-KEY')
...     next_value = int(current_value) + 1
...     pipe.multi()
...     pipe.set('OUR-SEQUENCE-KEY', next_value)
>>>
>>> r.transaction(client_side_incr, 'OUR-SEQUENCE-KEY')
[True]

注:订阅发布模式还没有详细理解,故没写,以后用到了会写。

迭代器

>>> for key, value in (('A', '1'), ('B', '2'), ('C', '3')):
...     r.set(key, value)
>>> for key in r.scan_iter():
...     print key, r.get(key)
A 1
B 2
C 3
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • python操作Redis 一. Redis是什么 Redis 是一个开源(BSD许可)的,内存中的数据结构存储系...
    shu_ke阅读 3,883评论 0 9
  • Python操作redis python连接方式:点击 下面介绍详细使用 1、String 操作 redis中的S...
    子非初心阅读 245评论 0 1
  • 连接数据库 StrictRedis ConnectionPool 构造url方式连接到数据库,有以下三种模式: S...
    cnkai阅读 3,126评论 0 2
  • 昨天,我们讨论了python如何连接redis。今天我们要学习如何用python操作redis的数据。 这里,再补...
    阿尔卑斯山上的小灰兔阅读 1,324评论 0 0
  • 半倚窗扉立,村庄入眼漆。 亭台人鼎沸, 暑热褪罗衣。 注:新韵
    幽小窗阅读 652评论 78 44