redis--与python交互
与python交互如下:
1 # lianxi.wsgi.redisTest 2 from redis import * 3 4 # r=StrictRedis(host='localhost',port=6379) 5 6 #写 7 # pipe=r.pipeline() 8 # pipe.set('py5','cherry1') 9 # pipe.set('py6','cherry2') 10 # pipe.execute() 11 12 #读 13 # result=r.get('py6') 14 # print(result.decode('utf-8')) 15 16 class redisHelper(): 17 def __init__(self): 18 self.r=StrictRedis(host='localhost',port=6379) 19 20 #写(使用pipline(),可以缓冲多条命令,然后一次性执行,减少服务器-客户端之间TCP数据库包,从而提高效率) 21 def redis_write(self,key,value): 22 pipe=self.r.pipeline() 23 pipe.set(key,value) 24 pipe.execute() 25 26 #读 27 def redis_read(self,key): 28 return self.r.get(key) 29 30 if __name__ == '__main__': 31 print(redisHelper().redis_read('py6').decode('utf-8'))
例子:登录优化(将redis和mysql结合)
1 # lianxi.wsgi.a7 2 import pymysql 3 import hashlib 4 5 class Consql(): 6 def __init__(self): 7 self.db = pymysql.connect(host='localhost', port=3306, user='root', password='mysql123', db='book') 8 self.cursor = self.db.cursor() 9 10 def close_sql(self): 11 self.cursor.close() 12 self.db.close() 13 14 #增删改数据库 15 def operate_sql(self,sql): 16 self.cursor.execute(sql) 17 self.db.commit() 18 19 self.close_sql() 20 21 #查询数据库 22 def select_all_sql(self,sql): 23 self.cursor.execute(sql) 24 content =self.cursor.fetchall() 25 26 self.close_sql() 27 return content 28 29 def select_one_sql(self,sql): 30 self.cursor.execute(sql) 31 content1 =self.cursor.fetchone() 32 33 self.close_sql() 34 return content1
1 from lianxi.wsgi.a7 import Consql 2 from lianxi.wsgi.redisTest import redisHelper 3 import hashlib 4 5 #==================登录优化======================= 6 #判断用户是否存在及密码是否正确 7 user=input('请输入用户名:') 8 password=input('请输入密码:') 9 10 #将输入的密码加密 11 m=hashlib.md5() 12 m.update(password.encode('utf-8')) 13 pwd=m.hexdigest() 14 # print(pwd) 15 16 #查询mysql数据库 17 consql=Consql() 18 select_sql='select password from test_user where name="{}";'.format(user) 19 sql_result=consql.select_one_sql(select_sql) 20 # print(sql_result) 21 22 #查询redis 23 redis_helper=redisHelper() 24 redis_result=redis_helper.redis_read(user) 25 # print(redis_result) 26 27 ########判断redis有没有这个用户######## 28 #如果redis没有这个用户,再去查mysql数据库,没查到则提示用户不存在,查到则先将该用户和密码存入redis,再判断密码是否正确 29 if redis_result==None: 30 print('1') 31 #if len(sql_result)==0: -------注意:这样写会报错的,sql_result返回的是None 32 if sql_result==None: 33 print('用户不存在') 34 else: 35 redis_helper.redis_write(user,pwd) 36 if pwd==sql_result[0]: 37 print('登录成功') 38 else: 39 print('密码错误') 40 #如果redis有这个用户,则直接判断密码是否正确 41 else: 42 print('2') 43 if pwd==redis_result.decode('utf-8'): #-------注意:这里redis_result需要解码,不然结果会是b'...' 44 print('登录成功') 45 else: 46 print('密码错误')
posted on 2019-10-25 23:59 cherry_ning 阅读(179) 评论(0) 收藏 举报
浙公网安备 33010602011771号