用户登录

#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
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)
#coding=utf-8
import MySQLdb

class MysqlHelper:
    def __init__(self,host='localhost',port=3306,db='test2',user='root',passwd='mysql',charset='utf8'):
        self.conn=MySQLdb.connect(host=host,port=port,db=db,user=user,passwd=passwd,charset=charset)

    def insert(self,sql,params):
        return self.__cud(sql,params)

    def update(self,sql,params):
        return self.__cud(sql,params)

    def delete(self,sql,params):
        return self.__cud(sql,params)

    def __cud(self,sql,params=[]):
        try:
            cs1 = self.conn.cursor()
            rows=cs1.execute(sql, params)
            self.conn.commit()
            cs1.close()
            self.conn.close()
            return rows
        except Exception,e:
            print e
            self.conn.rollback()

    def fetchone(self,sql,params=[]):
        try:
            cs1=self.conn.cursor()
            cs1.execute(sql,params)
            row=cs1.fetchone()
            cs1.close()
            self.conn.close()
            return row
        except Exception,e:
            print e

    def fetchall(self,sql,params):
        try:
            cs1=self.conn.cursor()
            cs1.execute(sql,params)
            rows=cs1.fetchall()
            cs1.close()
            self.conn.close()

            return rows
        except Exception,e:
            print e
原文地址:https://www.cnblogs.com/Erick-L/p/7447556.html