python简单操作redis

原文网址:http://www.the5fire.com/python-simple-redis.html


上篇文章简单说了下linux安装redis的过程,这里就是用python代码稍加演练,首先用pip安装redis:

sudo pip install redis
然后就可以在python中调用了,下面写了些基础的东西,按着redis实战里面的介绍来写。关于redis的复杂的使用以后用到再来学习,代码更直观:

import redis

cache = redis.StrictRedis(host='localhost', port=6379)

#1. 简单的get和set操作
print u'====set操作:'
cache.set('blog:title', u'the5fire的技术博客')
print cache.get('blog:title')

#真实应用场景,批量set和get
for i in range(10):
cache.mset({
'blog:post:%s:title' % i: u'文章%s标题' % i,
'blog:post:%s:content' % i: u'文章%s的正文' % i
})

post_list = []
for i in range(10):
post = cache.mget('blog:post:%s:title' % i, 'blog:post:%s:content' % i)
if post:
post_list.append(post)

for title, content in post_list:
print title, content

#2、 hashed类型的操作
print u'====hashed操作:'
cache.hset('blog:info','title', u'the5fire的技术博客')
cache.hset('blog:info','url', u'http://www.the5fire.com')

blog_info_title = cache.hget('blog:info', 'title')
print blog_info_title

blog_info = cache.hgetall('blog:info')
print blog_info

#同样hashed类型的set和get也可以进行批量操作
cache.hmset('blog:info', {
'title': 'the5fire blog',
'url': 'http://www.the5fire.com',
})
blog_info1 = cache.hmget('blog:info', 'title', 'url')
print blog_info1

#3、lists类型的操作
print u'====lists操作:'
cache.lpush('blog:tags', 'python')
cache.lpush('blog:tags', 'linux')
tags = cache.lrange('blog:tags', 0, 2)
print tags

#对应的还有rpush,lpop,rpop,更多可以看红丸的redis实战

#4、sets类型的操作
print u'====sets操作:'
cache.sadd('blog:category:python', '001')
cache.sadd('blog:category:python', '002')
#cache.sadd('blog:category:python', '001', '002')

print cache.smembers('blog:category:python')
cache.srem('blog:category:python', '001')
print cache.smembers('blog:category:python')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值