您的位置:首页 > 数据库 > Redis

Python redis.ttl 返回 None

2017-12-07 12:02 711 查看
今天在 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 类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python ttl None Strict redis