示例:用户登录
- 业务过程如下:
- 输入用户名、密码
- 密码加密
- 判断redis中是否记录了用户名,如果有则成功
- 如果redis中没有用户名,则到mysql中查询
- 从mysql中查询成功后,将用户名记录到redis中
#encoding=utf-8
import RedisConnet
import MysqlConnet
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
封装
- 连接redis服务器
- 常用的string类型的读写
import redis
class RedisConnet:
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):
return self.__redis.set(key,value)
- 连接MySQL服务
#encoding=utf8
import MySQLdb
class MysqlConnet():
def __init__(self,host,port,db,user,passwd,charset='utf8'):
self.host=host
self.port=port
self.db=db
self.user=user
self.passwd=passwd
self.charset=charset
def connect(self):
self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)
self.cursor=self.conn.cursor()
def close(self):
self.cursor.close()
self.conn.close()
def get_one(self,sql,params=()):
result=None
try:
self.connect()
self.cursor.execute(sql, params)
result = self.cursor.fetchone()
self.close()
except Exception, e:
print e.message
return result
def get_all(self,sql,params=()):
list=()
try:
self.connect()
self.cursor.execute(sql,params)
list=self.cursor.fetchall()
self.close()
except Exception,e:
print e.message
return list
def insert(self,sql,params=()):
return self.__edit(sql,params)
def update(self, sql, params=()):
return self.__edit(sql, params)
def delete(self, sql, params=()):
return self.__edit(sql, params)
def __edit(self,sql,params):
count=0
try:
self.connect()
count=self.cursor.execute(sql,params)
self.conn.commit()
self.close()
except Exception,e:
print e.message
return count