Python的redis模块管理键(Key)方法主要实现的Redis命令包括KEYS、GET、DEL(delete)、EXISTS、RANDOMKEY,TYPE、EXPIRE,其他的一些不能实现的在代码注释里面有所体现。
Linux系统版本
LSB Version: :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Distributor ID: RedHatEnterpriseServer
Description: Red Hat Enterprise Linux Server release 6.4 (Santiago)
Release: 6.4
Codename: Santiago
Redis版本
127.0.0.1:6379> info
# Server
redis_version:3.0.7
Python版本
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Python的Redis模块版本
DATA
__all__ = ['Redis', 'ConnectionPool', 'RedisError', 'ConnectionError',...
__version__ = '2.0.0'
VERSION
2.0.0
#!/usr/bin/python
import redis
import time
## Connect local redis service
client =redis.Redis(host='127.0.0.1',port=6379,db=0)
print "Connection to server successfully!"
dicKeys = client.keys("*")
print dicKeys
### Redis Key command part Start ###
# Set key-vlaue and get key-value
client.set('w3ckey','redis')
val = client.get('w3ckey')
print "Get key-vlaue ", val
# Delete key w3ckey
client.delete('w3ckey')
val = client.get('w3ckey')
print "Get none key-vlaue: ", val
# No dump key-value
client.set('greeting','Hello, dumping world!')
val = client.get('greeting')
print "Get key-vlaue ", val
# Exists check
keyList = ['w3ckey','greeting']
for key in keyList:
# print "Key name: ",key
isKey =client.exists(key)
if isKey :
print "Have value mapping with key: ", key
else:
print "No value mapping with key: ",key
# Set Expire time for greeting
client.expire('greeting',2)
#saveTime = client.pttl('greeting')
#print "Remaining time: ",saveTime
time.sleep(2)
isExpire = client.get('greeting')
if not isExpire:
print "Key expire "
else:
print "Key not expire"
# Key get special pattern, Redis command:keys
#set value
keyDic = {'w3c1':'redis', 'w3c2':'mysql', 'w3c3':'mongodb'}
for key in keyDic.keys():
client.set(key,keyDic[key])
keyList = client.keys("w3c*")
print "Get keys: ",keyList
# Get random key from DB, Redis command:randomkey
randomKey =client.randomkey()
print "Get random key: ",randomKey
# Get key type, Redis command:type
keyType =client.type(randomKey)
print "Get key type: ",keyType
# Push value to list's head
client.lpush('w3ckey','redis')
client.lpush('w3ckey','mongodb')
client.lpush('w3ckey','mysql')
val = client.lrange('w3ckey',0,3)
print "Get key-vlaue list: ", val
#Empty db
client.flushdb()
hashVal = client.hgetall('profile')
print hashVal
参考资料
1、Redis 键(key)
2、Python redis文档(python交互模式下命令>>>help redis
)