flask框架實現修改密碼和免密登錄功能

修改密碼功能

數據庫部分:

#重置密碼
def reset_pass(phone,password):
    conn,cursor=get_conn()
    sql="update userdata set userpass='"+password+"' where userphone='"+phone+"'"
    try:
        print("正在修改密碼...")
        resetflag=cursor.execute(sql)
        conn.commit()
        close_conn(conn,cursor)
        if(resetflag==1):
            print("修改成功")
            return 1
        else:
            print("修改失敗!")
            return 0
    except:
        print("系統錯誤...修改密碼失敗!")
        return 0

路由部分:

#用戶修改密碼
@app.route('/resetpass',methods=['GET', 'POST'])
def resetpass():
    userphone=request.values.get('userphone')
    resetpass=request.values.get('resetpass')
    print("路由獲得手機號:"+userphone+"\n")
    print("路由獲得新密碼:" + resetpass + "\n")
    flag=sql.reset_pass(userphone,resetpass)
    if(flag==1):
        return jsonify({"data":1})
    else:
        return jsonify({"data":0})

html頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>樹懶電影---重置您的密碼</title>
    <style type="text/css">
        #resetform{
            margin-top: 350px;
            margin-left: 750px;
        }
    </style>
</head>
<body>
    <form method="post" id="resetform">
        <tr>
            <td><input type="text" id="userphone" value="" placeholder="輸入您的手機號碼"></td>
        </tr><br>
        <tr>
            <td><input type="password" id="resetpass1" value="" placeholder="輸入您的新密碼"></td>
        </tr><br>
        <tr>
            <td><input type="password" id="resetpass2" value="" placeholder="再次輸入您的新密碼"></td>
        </tr><br>
        <tr>
            <td><input type="reset" value="清空"></td>
            <td><input type="button" id="resetbtn" onclick="resetpass()" value="提交"></td>
        </tr>
    </form>
</body>
</html>
<script src="../static/js/jquery.min.js"></script>
<script type="text/javascript">
    function resetpass(){
        var userphone=document.getElementById("userphone").value
        var resetpass1=document.getElementById("resetpass1").value
        var resetpass2=document.getElementById("resetpass2").value
        var submit_flag=1
        //判空
        if((userphone.length==0)||(resetpass1.length==0)||(resetpass2.length==0)){
            submit_flag=0
            alert("請把信息填寫完整!")
        }
        //判斷密碼一致性
        if(resetpass2!=resetpass1){
            submit_flag=0
            alert("兩次填寫的密碼不一致")
            document.getElementById("resetpass1").focus();
        }
        //判斷手機號
        if(userphone.length!=11){
            submit_flag=0
            alert("手機號碼應為11位!")
            document.getElementById("userphone").focus();
        }
        var regu =  /^1[3456789]\d{9}$/
        if(!(regu.test(userphone)) ){
            submit_flag=0
            alert("手機號碼格式有誤!")
            document.getElementById("userphone").focus();
        }
        //判斷密碼格式
        if(!((resetpass1.length>=6)&&resetpass1.length<=18))
        {
            submit_flag=0
            alert("密碼長度應該為6-16位!")
            document.getElementById("resetpass1").focus();
        }
            var regex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z]).{6,18}');
            part_pass=resetpass1.split(" ")
        if((!(regex.test(resetpass1))) || part_pass.length!=1)
        {
            submit_flag=0
            alert("密碼為數字+英文字母 且不可以包含空格!")
            document.getElementById("resetpass1").focus();
        }

        //發起請求
            if(submit_flag==1)
        {
            $.ajax({
                url:"/resetpass",
                data:{userphone:userphone,resetpass:resetpass2},
                success: function (data) {
                    if (data.data==1)
                    {
                        alert("密碼修改成功!")
                        window.open("/",'_self')
                    }
                    else
                    {
                        alert("修改密碼失敗!請重試")
                    }
                },
                error: function (xhr, type, errorThrown) {
                    // print("ajax請求失敗!")
                }
            })
        }
        // alert(submit_flag)
    }
</script>

免密登錄

html代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="../static/css/login.css" rel="external nofollow" >
    <script src="../static/js/jquery-1.7.2.min.js"></script>
    <script src="../static/js/register.js"></script>
    <title>樹懶電影登錄</title>
    <script >
    </script>
</head>
<body>
    <div id="container">
        <div id="container-child">
            <div id="img-div"><img src="../static/img/shulan.png"></div>
            <div id="login-div">
                <div>
                    <p class="p-title">登錄您的樹懶電影</p>
                    <form id="login-form" method="post">
                        <div class="input-d">
                            <input class="input-text" type="text" name="userphone" id="userphone" placeholder="請輸入您的賬號">
                        </div>
                        <div class="input-d">
                            <input class="input-text" type="password" name="password" id="password" placeholder="請輸入您的密碼">
                        </div>
                        <div class="div-input">
                            <div>
                                <input type="checkbox" value=“1” class=“remeber” onclick="onClickHander(this)">
                                <label>記住密碼</label>
                            </div>
                        </div>
                        <button type="button" class="login-button" onclick="login_()">登 錄</button>
                        <div class="footer"> <a href="http://127.0.0.1:5000/regis" rel="external nofollow" >註冊</a> | <a href="http://127.0.0.1:5000/reset" rel="external nofollow" >忘記密碼</a></div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script>
    var cb=0
    function onClickHander(obj) {
        if(obj.checked==true){
            cb=1
            // alert(cb)
        }else{
            cb=0
            // alert(cb)
        }
    }
    function login_(){
        var userphone=document.getElementById("userphone").value
        var password=document.getElementById("password").value
        // alert(cb)
        $.ajax({
                url: "/web_login",
                data: {
                    userphone:userphone,password:password,cb:cb
                },
                success: function (data) {
                    //正常驗證失敗彈窗
                    if (data.data == 0)
                        alert("賬號或密碼錯誤!")
                    //驗證成功,返回response
                    if (data.data != 0)
                        window.open("http://127.0.0.1:5000/show","_self")
                },
                error: function (xhr, type, errorThrown) {
                    print("登錄js,驗證賬號密碼ajax請求失敗!")
                }
        })
    }
</script>

Python路由

#免密登錄
@app.route('/web_login/',methods=['GET', 'POST'])
def web_login():
    userphone = request.values.get('userphone')
    password=request.values.get('password')
    cb=request.values.get('cb')
    print("是否記住密碼: "+cb)            #cb的返回值類型是 str 字符串
    # print(type(cb))
    print("登錄賬號:"+userphone+"   "+"密碼:"+password)
    res=sql.web_login(userphone,password)
    if(res==True):
        session['userphone'] = userphone
        if(cb=="1"):
            print("開始存儲cookie登錄賬號:" + userphone + "   " + "密碼:" + password)
            resp = make_response('儲存cookie')
            resp.set_cookie('cookphone', userphone, max_age=3600 * 24 * 15)
            resp.set_cookie('cookpass', password, max_age=3600 * 24 * 15)
            print("登錄成功且用戶選擇記住密碼,返回response")
            return resp                   #登錄成功且用戶選擇記住密碼,返回response
        else:
            print("登錄成功 返回 1 狀態碼")
            return jsonify({"data": 1})  # 登錄成功 返回 1 狀態碼
    else:
        print("登錄失敗   返回 0 狀態碼")
        return jsonify({"data":0})  #登錄失敗   返回 0 狀態碼

數據庫驗證登錄

# 用戶(web)登錄驗證
def web_login(userphone, password):
    cursor = None
    conn = None
    res=[]
    if(userphone==None or password==None):
        return False
    conn, cursor = get_conn()
    sql = "select userphone,userpass from userdata where '"+userphone+"'=userphone and '"+password+"'=userpass "
    res=query(sql)
    conn.commit()
    if(len(res)==0):
        print("登陸失敗(WEB)")
        close_conn(conn, cursor)
        return False
    else:
        close_conn(conn, cursor)
        print("登陸成功(WEB)")
        return True

以上就是flask框架實現修改密碼和免密登錄功能的詳細內容,更多關於flask 修改密碼和免密登錄的資料請關註WalkonNet其它相關文章!

推薦閱讀: