酒店式公寓水电煤:Python操作redis - chenggong2dm的专栏 - CSDN博客
Python操作redis收藏
首先确保redis已经正常启动。
安装
可以去pypi上找到redis的Python模块:
http://pypi.python.org/pypi?%3Aaction=search&term=redis&submit=search
然后按照提示down下来redis-py-2.2.1.tar.gz
非常标准的解压: #tar xvzf redis-py-2.2.1.tar.gz
进入解压目录,进行Python模块的标准安装:
python setup.py install
运行
打开Python解释器:
>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar') #或者写成 r['foo'] = 'bar'
True
>>> r.get('foo')
'bar'
>>> r.delete('foo')
True
>>> r.dbsize() #库里有多少key,多少条数据
0
>>> r['test']='OK!'
>>> r.save() #强行把数据库保存到硬盘。保存时阻塞
True
--------------------------------
>>> r.flushdb() #删除当前数据库的所有数据
True
>>> a = r.get('chang')
>>> a # 因为是Noen对象,什么也不显示!
>>> dir(a)
['__class__','__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__','__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__','__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> r.exists('chang') #看是否存在这个键值
False
>>> r.keys() # 列出所有键值。(这时候已经存了4个了)
['aaa', 'test', 'bbb', 'key1']
其他命令API,请参照redis-Python作者的博客,写的挺清楚了:
https://github.com/andymccurdy/redis-py