首页 > 编程语言 > 详细

Python操作redis

时间:2014-03-15 04:58:18      阅读:420      评论:0      收藏:0      [点我收藏+]

Python操作redis


pythonredis数据库searchimport

首先确保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)   #如果设置了密码,就加上password=密码

>>> 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‘]


附注A:

来看一下redis.Redis的 init() 函数定义:

__init__(self, host=‘localhost‘, port=6379, db=0, password=None, socket_timeout=None, connection_pool=None, charset=‘utf-

8‘, errors=‘strict‘, decode_responses=False, unix_socket_path=None)

最新的redis 2.6.0加入了连接池,具体用法可以看作者博客。


附注B:

其他命令API,请参照redis-Python作者的博客,写的挺清楚了:

https://github.com/andymccurdy/redis-py




sudo pip install redis

or alternatively (you really should be using pip though):


$ sudo easy_install redis

or from source:


$ sudo python setup.py install

Getting Started


>>> import redis

>>> r = redis.StrictRedis(host=‘localhost‘, port=6379, db=0)

>>> r.set(‘foo‘, ‘bar‘)

True

>>> r.get(‘foo‘)

‘bar‘


本文出自 “DavideyLee” 博客,请务必保留此出处http://davideylee.blog.51cto.com/8703117/1376760

Python操作redis,布布扣,bubuko.com

Python操作redis

原文:http://davideylee.blog.51cto.com/8703117/1376760

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!