Django Redis配合Mysql验证用户登录

1.redis_check.py

# coding:utf-8


import pymysql
import redis
import sys


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


def con_redis(name, passwd):
    pool = redis.ConnectionPool(host='192.168.8.102',
                                port=6379,
                                password='root', )
    r = redis.Redis(connection_pool=pool)
    r_passwd = r.hget(name, name)
    if not r_passwd:
        return False, '登录失败'
    if passwd == r_passwd.decode('utf8'):
        return True, '登录成功'
    else:
        return False, '登录失败'


def main(name, passwd):
    # name = sys.argv[1]
    # passwd = sys.argv[2]
    result = con_redis(name, passwd)
    if not result[0]:
        sql = '''select name from tb_login where name="%s" and passwd="%s"''' % (name, passwd)
        data = con_mysql(sql)
        if data:
            pool = redis.ConnectionPool(host='192.168.8.102',
                                        port=6379,
                                        password='root', )
            r = redis.Redis(connection_pool=pool)
            r.hset(name, name, passwd)
            # print('redis数据更新成功,账号密码正确!')
            return True
        else:
            # print('账号或者密码错误!')
            return False
    else:
        # print('登录成功!')
        return True


if __name__ == '__main__':
    main()

2.视图路由urls.py

url(r'^log/(?P<user_dict>\w{1,12}/\w{1,23})/$', views.log)

3.视图views.py

def log(request, user_dict):
    if request.method == "GET":
        name, passwd = user_dict.split("/")
        print(name,passwd)
        res = redis_check.main(name, passwd)
        print(res)
        if res:
            return HttpResponse("ok")
        else:
            return HttpResponse("error")

4.测试

http://127.0.0.1:8000/log/zq/zq/

 

转载于:https://www.cnblogs.com/icemonkey/p/10517930.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值