1、redis与Python交互的简单例子
from redis import * r=StrictRedis(host='localhost',port=6379) #写 pipe=r.pipeline() pipe.set('py1','hello') pipe.set('py2','world') pipe.execute() #执行 #读 temp=r.get('py1') print(temp) #'hello
2、用户登录:
先去判断Redis中有没有,没有再去MySQL数据库中查找
【先从Redis中查找,找不到就去MySQL中查找;若MySQL中存在,将此数据保存到Redis中】
2-1 MysqlHelper.py 基于MySQL的数据库操作,后续作为模块使用
#MySQL数据库的封装 import pymysql class MysqlHelper(object): def __init__(self,host,port,user,passwd,db,charset='utf8'): self.host=host self.user=user self.passwd=passwd self.port=port self.db=db self.charset=charset def open(self): self.conn=pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset) self.cursor=self.conn.cursor() def close(self): self.cursor.close() self.conn.close() def cud(self,sql,params=[]): #c增加 u更新 d删除 self.open() try: self.cursor.execute(sql,params) self.conn.commit() print('操作成功') except Exception as e: self.conn.rollback() print(e) self.close() def all(self,sql,params=[]): #找到所有数据 self.open() try: self.cursor.execute(sql,params) res=self.cursor.fetchall() #拿到所有数据 return res except Exception as e: self.conn.rollback() print(e) self.close() def one(self,sql,params=[]): #找到一行数据 self.open() try: self.cursor.execute(sql,params) res=self.cursor.fetchone() #拿到所有数据 return res except Exception as e: self.conn.rollback() print(e) self.close()
2-2 RedisHelper.py 基于redis的数据库操作,后续作为模块使用
from redis import * class RedisHelper(object): def __init__(self,host,port): self.__redis=StrictRedis(host,port) def set(self,key,value): #基于string的写操作 self.__redis.set(key,value) def get(self,key): return self.__redis.get(key) #基于string的读操作
2-3 完善登录(基于MySQL+redis).py
from RedisHelper import RedisHelper from MysqlHelper import MysqlHelper from hashlib import sha1 #接收输入 name=input('请输入用户名:').strip() pwd1=input('请输入密码:').strip() #加密 s1=sha1() s1.update(pwd1.encode('utf8')) pwd2=s1.hexdigest() #先去判断Redis中有没有,没有再去MySQL数据库中查找 【先从Redis中查找,找不到就去MySQL中查找;若MySQL中存在,将此数据保存到Redis中】 #查询Redis中是否存在此用户 r=RedisHelper('localhost',6379) #print(r.get('name')) #若没有,则返回None m=MysqlHelper(host='localhost',port=3306,user='root',passwd='12345678',db='sjk_name',charset='utf8') #判断Redis中是否存储了此用户和密码 if r.get(name)==None: sql='select passwd from table_name where name=%s' pwd3=m.one(sql,[name]) #mysql查找结果,返回的是元组,真正的结果是pwd3[0] if pwd3==None: print('用户名不存在') else: #判断密码是否正确 if pwd3[0]==pwd2: print('登陆成功') # 在mysql中查询该用户名,如果查询到数据,且密码正确,则在Redis中存储 【此时需要自己设置结构 键:用户名 值:密码】 r.set(name, pwd3[0]) else: print('密码错误') else: if r.get(name)==pwd2: print('登录成功') else: print('密码错误')