使用python實現滑動驗證碼


首先安裝一個需要用到的模塊

pip install social-auth-app-django

安裝完后在終端輸入pip list會看到

social-auth-app-django 3.1.0
social-auth-core       3.0.0

然后可以來我的github,下載關於滑動驗證碼的這個demo:https://github.com/Edward66/slide_auth_code

下載完后啟動項目

python manage.py runserver 

啟動這個項目后,在主頁就能看到示例

 

前端部分

隨便選擇一個(最下面的是移動端,不做移動端不要選)把html和js代碼復制過來,我選擇的是彈出式的。這里面要注意他的ajax請求發送的網址,你可以把這個網址改成自己視圖函數對應的網址,自己寫里面的邏輯,比如我是為了做用戶登陸驗證,所以我是寫的邏輯是拿用戶輸入的賬號、密碼和數據庫里的做匹配。

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陸頁面</title>
    <link rel="stylesheet" href="/static/blog/css/slide_auth_code.css">
    <link rel="stylesheet" href="/static/blog/bs/css/bootstrap.css">
</head>

<body>

<h3>登陸頁面</h3>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="popup">
                <form id="fm">
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="id_user">用戶名:</label>
                        <input name="user" id="id_user" class="form-control" type="text">
                    </div>

                    <div class="form-group">
                        <label for="id_pwd">密碼:</label>
                        <input name="pwd" id="id_pwd" class="form-control" type="password">
                    </div>

                    <input class="btn btn-default" id="popup-submit" type="button" value="提交">
                    <span id="error-info"></span>

                    <a href="{% url 'blog:register' %}" class="btn btn-success pull-right">注冊</a>
                </form>
                <div id="popup-captcha"></div>
            </div>
        </div>
    </div>
</div>

<script src="/static/blog/js/jquery-3.3.1.js"></script>
<script src="/static/blog/js/gt.js"></script>
<script src="/static/blog/js/slide_auth_code.js"></script>

 

login.js

let handlerPopup = function (captchaObj) {
    // 成功的回調
    captchaObj.onSuccess(function () {
        let validate = captchaObj.getValidate();
        $.ajax({
            url: "", // 進行二次驗證
            type: "post",
            dataType: "json",
            data: $('#fm').serialize(),

            success: function (data) {
                if (data.user) {
                    location.href = '/index/'
                } else {
                    $('#error-info').text(data.msg).css({'color': 'red', 'margin-left': '10px'});
                    setTimeout(function () {
                        $('#error-info').text('');
                    }, 3000)
                }
            }
        });
    });
    $("#popup-submit").click(function () {
        captchaObj.show();
    });
    // 將驗證碼加到id為captcha的元素里
    captchaObj.appendTo("#popup-captcha");
    // 更多接口參考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
// 驗證開始需要向網站主后台獲取id,challenge,success(是否啟用failback)
$.ajax({
    url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加隨機數防止緩存
    type: "get",
    dataType: "json",
    success: function (data) {
        // 使用initGeetest接口
        // 參數1:配置參數
        // 參數2:回調,回調的第一個參數驗證碼對象,之后可以使用它做appendTo之類的事件
        initGeetest({
            gt: data.gt,
            challenge: data.challenge,
            product: "popup", // 產品形式,包括:float,embed,popup。注意只對PC版驗證碼有效
            offline: !data.success // 表示用戶后台檢測極驗服務器是否宕機,一般不需要關注
            // 更多配置參數請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
        }, handlerPopup);
    }
});

 

注意:我是把ajax請求的url改成了當前頁面的視圖函數。另外原生代碼是全部寫在html里的,我把它做了解耦。還有原生代碼用的是jquery-1.12.3,我改成了jquery-3.3.1,也可以正常使用。

 

后端部分

urls.py

由於后端的邏輯是自己寫的,這里只需要用到pcgetcaptcha這部分代碼,來處理驗證部分。

 

首先在urls.py里加入路徑

from django.urls import path, re_path

from blog.views import slide_code_auth

# 滑動驗證碼
path('login/', views.login),
re_path(r'^pc-geetest/register', slide_code_auth, name='pcgetcaptcha'),

# slide_auth_code是我自己寫的名字,原名是pcgetcaptcha

我把pcgetcaptcha的邏輯部分放到了utils/slide_auth_code.py里面,當做工具使用

 

utils/slide_auth_code.py

from blog.geetest import GeetestLib

pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"


def pcgetcaptcha(request):
    user_id = 'test'
    gt = GeetestLib(pc_geetest_id, pc_geetest_key)
    status = gt.pre_process(user_id)
    request.session[gt.GT_STATUS_SESSION_KEY] = status
    request.session["user_id"] = user_id
    response_str = gt.get_response_str()

    return response_str


# pc_geetest_id和pc_geetest_key不可省略,如果做移動端要加上mobile_geetest_id和mobile_geetest_key

 

views.py

from django.contrib import auth
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse

from blog.utils.slide_auth_code import pcgetcaptcha


def login(request):
    if request.method == "POST":
        response = {'user': None, 'msg': None}
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')

        user = auth.authenticate(username=user, password=pwd)

        if user:
            auth.login(request, user)
            response['user'] = user.username
        else:
            response['msg'] = '用戶名或密碼錯誤'
        return JsonResponse(response)
    return render(request, 'login.html')


# 滑動驗證碼
def slide_code_auth(request):
    response_str = pcgetcaptcha(request)
    return HttpResponse(response_str)


def index(request):
    return render(request, 'index.html')

注意:不一定非要按照我這樣,根據自己的需求選擇相應的功能並做出相應的修改 

 

**修改相應代碼,把滑動驗證用到注冊頁面**

register.js

// 頭像預覽功能
$('#id_avatar').change(function () {   // 圖片發生了變化,所以要用change事件
    // 獲取用戶選中的文件對象
    let file_obj = $(this)[0].files[0];

    // 獲取文件對象的路徑
    let reader = new FileReader();  // 等同於在python里拿到了實例對象
    reader.readAsDataURL(file_obj);

    reader.onload = function () {
        // 修改img的src屬性,src = 文件對象的路徑
        $("#avatar_img").attr('src', reader.result);  // 這個是異步,速度比reader讀取路徑要快,
                                                      // 所以要等reader加載完后在執行。
    };
});

// 基於Ajax提交數據
let handlerPopup = function (captchaObj) {
    // 成功的回調
    captchaObj.onSuccess(function () {
        let validate = captchaObj.getValidate();
        let formdata = new FormData();  // 相當於python里實例化一個對象
        let request_data = $('#fm').serializeArray();
        $.each(request_data, function (index, data) {
            formdata.append(data.name, data.value)
        });
        formdata.append('avatar', $('#id_avatar')[0].files[0]);

        $.ajax({
            url: '',
            type: 'post',
            contentType: false,
            processData: false,
            data: formdata,
            success: function (data) {
                if (data.user) {
                    // 注冊成功
                    location.href = '/login/'
                } else {
                    // 注冊失敗

                    // 清空錯誤信息,每次展示錯誤信息前,先把之前的清空了。
                    $('span.error-info').html("");
                    $('.form-group').removeClass('has-error');
                    // 展示此次提交的錯誤信息
                    $.each(data.msg, function (field, error_list) {
                        if (field === '__all__') {  // 全局錯誤信息,在全局鈎子里自己定義的
                            $('#id_re_pwd').next().html(error_list[0]);
                        }
                        $('#id_' + field).next().html(error_list[0]);
                        $('#id_' + field).parent().addClass('has-error');  // has-error是bootstrap提供的
                    });
                }
            }
        })

    });
    $("#popup-submit").click(function () {
        captchaObj.show();
    });
    // 將驗證碼加到id為captcha的元素里
    captchaObj.appendTo("#popup-captcha");
    // 更多接口參考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
// 驗證開始需要向網站主后台獲取id,challenge,success(是否啟用failback)
$.ajax({
    url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加隨機數防止緩存
    type: "get",
    dataType: "json",
    success: function (data) {
        // 使用initGeetest接口
        // 參數1:配置參數
        // 參數2:回調,回調的第一個參數驗證碼對象,之后可以使用它做appendTo之類的事件
        initGeetest({
            gt: data.gt,
            challenge: data.challenge,
            product: "popup", // 產品形式,包括:float,embed,popup。注意只對PC版驗證碼有效
            offline: !data.success // 表示用戶后台檢測極驗服務器是否宕機,一般不需要關注
            // 更多配置參數請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
        }, handlerPopup);
    }
});

 

views.py

根據需求自己寫邏輯

 

總結:滑動驗證主要用到的是js部分,只需修改ajax里傳遞的值就好,后台邏輯自己寫。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM