第一部分转自:http://blog.csdn.net/chenggong2dm/article/details/6102540
首先确保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
第二部分转自:http://www.th7.cn/Program/Python/201403/184340.shtml
这个部分主要学习了如何利用Python中的字典向redis数据库进行批加入
使用Python如何操作Redis呢?下面用实例来说明用Python读写Redis数据库。
比如,我们插入一条数据,如下:
import redis
class Database:
def __init__(self):
self.host = 'localhost'
self.port = 6379
def write(self,website,city,year,month,day,deal_number):
try:
key = '_'.join([website,city,str(year),str(month),str(day)])
val = deal_number
r = redis.StrictRedis(host=self.host,port=self.port)
r.set(key,val)
except Exception, exception:
print exception
def read(self,website,city,year,month,day):
try:
key = '_'.join([website,city,str(year),str(month),str(day)])
r = redis.StrictRedis(host=self.host,port=self.port)
value = r.get(key)
print value
return value
except Exception, exception:
print exception
if __name__ == '__main__':
db = Database()
db.write('meituan','beijing',2013,9,1,8000)
db.read('meituan','beijing',2013,9,1)
上面操作是先写入一条数据,然后再读取,如果写入或者读取数据太多,那么我们最好用批处理,这样效率会更高。
import redis
import datetime
class Database:
def __init__(self):
self.host = 'localhost'
self.port = 6379
self.write_pool = {}
def add_write(self,website,city,year,month,day,deal_number):
key = '_'.join([website,city,str(year),str(month),str(day)])
val = deal_number
self.write_pool[key] = val
def batch_write(self):
try:
r = redis.StrictRedis(host=self.host,port=self.port)
r.mset(self.write_pool)
except Exception, exception:
print exception
def add_data():
beg = datetime.datetime.now()
db = Database()
for i in range(1,10000):
db.add_write('meituan','beijing',2013,i,1,i)
db.batch_write()
end = datetime.datetime.now()
print end-beg
if __name__ == '__main__':
add_data()