今天在 Python 中使用 redis 遇到一个奇怪的问题。
一. 问题描述
>>> import redis
>>> >>> r = redis.Redis(host='localhost', port=6379)
>>> print r.get('foo')
bar
>>> print r.ttl('foo')
None
怎么会是 None 呢?去 redis 里面看看
127.0.0.1:6379> get foo
"bar"
127.0.0.1:6379> ttl foo
(integer) -1
ttl 有值啊,这就奇怪了。
Google 后找到应该这样使用:
>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)
>>> print r.ttl('foo')
-1
那么问题来了Redis
和StrictRedis
究竟有什么区别?
二. Redis 和 StrictRedis 的联系与区别
class StrictRedis(builtin.object)
This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol.
StrictRedis 类实现了 Redis 协议的全部命令。
我们再来看看 Redis 类:
class Redis(StrictRedis)
Provides backwards compatibility with older versions of redis-py that changed arguments to some commands to be more Pythonic, sane, or by accident.
Redis 类继承自 StrictRedis,提供了向后兼容。
If you’re looking to use the standard syntax, consider using the StrictRedis class.
如果要使用标准语法的话,官方推荐 StrictRedis 类。