前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python简单操作redis

python简单操作redis

作者头像
the5fire
发布2019-02-28 16:43:26
4400
发布2019-02-28 16:43:26
举报

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

代码语言:javascript
复制
sudo pip install redis

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

代码语言:javascript
复制
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')

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-12-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档