python: 登陆redis , 登录mysql

登陆redis , 登录mysql

import sys

import pymysql
import redis

def con_mysql(sql):
    db = pymysql.connect(
        host = '47.98.173.x',
        user = 'root',
        passwd = '123456',
        port = 3306,
        db = 'passwd',
        charset = 'utf8')
    cursor = db.cursor()
    cursor.execute(sql)
    data = cursor.fetchall()
    db.close()
    return data

def con_redis(name, passwd):
    r = redis.Redis(host = '47.98.173.x', port = 6379, password = '123456')
    r_name = r.hget('user', 'nam')
    r_passwd = r.hget('user', 'passwd')
    # 类型转换,将类型转换为utf8
    r_name = r_name.decode('utf8')
    r_passwd = r_passwd.decode('utf8')
    # print(r_name, r_passwd)
    if name == r_name and passwd == r_passwd:
        return True, '欢迎回来, %s!' % name
    else:
        return False, '用户名或密码错误!'


def main():
    # print(con_mysql('select * from stu'))
    # print(con_redis())

    # 获取传入的姓名和密码参数
    name = sys.argv[1]
    passwd = sys.argv[2]
    #传入redis中, 进行校验
    result = con_redis(name, passwd)
    # result[0] 返回第一个False结果
    if not result[0]:
        # 查询mysql数据库
        sql = '''select * from stu where nam = '%s'
        and passwd = '%s' ''' % (name, passwd)
        data = con_mysql(sql)
        if data:
            r = redis.Redis(host = '47.106.145.176', port = 6379, password = '123456')
            r.hset('user', 'nam', name)
            r.hset('user', 'passwd', passwd)
            print('刷新redis, 登陆成功!')
        else:
            print('用户名和密码错误!')
    else:
        print('redis中数据正确,登陆成功!')


if __name__ == '__main__':
    main()

你可能感兴趣的:(python: 登陆redis , 登录mysql)