zoukankan      html  css  js  c++  java
  • redis(六)

    安装包

    sudo pip install redis
    
    • 使用源码安装
    unzip redis-py-master.zip
    cd redis-py-master
    sudo python setup.py install
    

    交互代码

    • 引入模块
    import redis
    
    • 连接
    try:
        r=redis.StrictRedis(host='localhost',port=6379)
    except Exception,e:
        print e.message
    • 方式一:根据数据类型的不同,调用相应的方法,完成读写

    更多方法同前面学的命令

    r.set('name','hello')
    r.get('name')
    • 方式二:pipline
    • 缓冲多条命令,然后一次性执行,减少服务器-客户端之间TCP数据库包,从而提高效率
      pipe = r.pipeline()
      pipe.set('name', 'world')
      pipe.get('name')
      pipe.execute()

    封装

    • 连接redis服务器部分是一致的
    • 这里将string类型的读写进行封装
      import redis
      class RedisHelper():
          def __init__(self,host='localhost',port=6379):
              self.__redis = redis.StrictRedis(host, port)
          def get(self,key):
              if self.__redis.exists(key):
                  return self.__redis.get(key)
              else:
                  return ""
          def set(self,key,value):
              self.__redis.set(key,value)

    示例:用户登录

    • 业务过程如下:
    • 输入用户名、密码
    • 密码加密
    • 判断redis中是否记录了用户名,如果有则成功
    • 如果redis中没有用户名,则到mysql中查询
    • 从mysql中查询成功后,将用户名记录到redis中
    #encoding=utf-8
    from t2 import RedisHelper
    from t3 import MysqlHelper
    import hashlib
    
    name=raw_input("请输入用户名:")
    pwd=raw_input("请输入密码:")
    
    sha1=hashlib.sha1()
    sha1.update(pwd)
    pwd1=sha1.hexdigest()
    
    try:
        redis=RedisHelper()
        if redis.get('uname')==name:
            print 'ok'
        else:
            mysql=MysqlHelper('localhost',3306,'test1','root','mysql')
            upwd=mysql.get_one('select upwd from userinfos where uname=%s',[name])
            if upwd==None:
                print '用户名错误'
            elif upwd[0]==pwd1:
                redis.set('uname', name)
                print '登录成功'
            else:
                print "密码错误"
    except Exception,e:
        print e.message
  • 相关阅读:
    day19(上)_IO流2(BufferedReaer,BufferedWriter,BufferedInputStream,BufferedOutputStream)
    day19(下)_IO流4(InputStreamReader,OutputStreamWriter,流操作规律总结)
    Synchronized锁 IT
    Linux查看端口信息命令 IT
    ReentrantLock锁 IT
    让网站实时生成多种电子书:jar、umd、chm、pdf、epub
    mysql性能的检查和调优方法
    新型的大型bbs架构(squid+nginx)
    uchome中的防反复提交机制
    joymobiler V2.7发布,支持pdf文档的生成
  • 原文地址:https://www.cnblogs.com/leecoffee/p/9039239.html
Copyright © 2011-2022 走看看