用Python寫一個滑動驗證碼


1.准備階段

  滑動驗證碼我們可以直接用GEETEST的滑動驗證碼。

  打開網址:https://www.geetest.com/ ,找到技術文檔中的行為驗證,打開部署文檔,點擊Python,下載ZIP包。

  ZIP包下載地址:https://github.com/GeeTeam/gt3-python-sdk/archive/master.zip

  解壓,找到django_demo,為了方便復制粘貼代碼,可以用編輯器打開項目。

2.實施

  自己先寫一個簡單的登錄,然后將django_demo中的關鍵代碼復制到我們自己的項目中。過程省去,我直接貼代碼。

2.1.login.py(登錄界面)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>歡迎登錄</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/mystyle.css">
</head>
<body>
<div class="container">
    <div class="row">
        <form class="form-horizontal col-md-6 col-md-offset-3 login-form">
            {% csrf_token %}
            <div class="form-group">
                <label for="username" class="col-sm-2 control-label">用戶名</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="username" name="username" placeholder="用戶名">
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label">密碼</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" id="password" name="password" placeholder="密碼">
                </div>
            </div>
            <div class="form-group">
                {#                放置極驗的滑動驗證碼#}
                <div id="popup-captcha"></div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="button" class="btn btn-default" id="login-button">登錄</button>
                    <span class="login-error"></span>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="/static/jquery-3.3.1.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
<!-- 引入封裝了failback的接口--initGeetest -->
<script src="http://static.geetest.com/static/tools/gt.js"></script>
<script>
    {#極驗滑動驗證碼用於發送登錄數據的。滑動驗證碼驗證通過之后,才會執行到這里。#}
    var handlerPopup = function (captchaObj) {
        // 成功的回調
        captchaObj.onSuccess(function () {
            var validate = captchaObj.getValidate();
            // 取到用戶填寫的用戶名和密碼 -> 取input框的值
            var username = $("#username").val();
            var password = $("#password").val();
            $.ajax({
                url: "/login/", // 進行二次驗證
                type: "post",
                dataType: "json",
                data: {
                    username: username,
                    password: password,
                    csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
                    geetest_challenge: validate.geetest_challenge,
                    geetest_validate: validate.geetest_validate,
                    geetest_seccode: validate.geetest_seccode
                },
                success: function (data) {
                    console.log(data);
                    if (data.status) {
                        // 有錯誤,在頁面上提示
                        $(".login-error").text(data.msg);
                    } else {
                        // 登陸成功
                        location.href = data.msg;
                    }
                }
            });
        });
        {#用於顯示極驗滑動驗證碼#}
        $("#login-button").click(function () {
            captchaObj.show();
        });
        // 將驗證碼加到id為captcha的元素里
        captchaObj.appendTo("#popup-captcha");
        // 更多接口參考:http://www.geetest.com/install/sections/idx-client-sdk.html
    };

    // 當input框獲取焦點時將之前的錯誤清空
    $("#username,#password").focus(function () {
        // 將之前的錯誤清空
        $(".login-error").text("");
    });

    // 驗證開始需要向網站主后台獲取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);
        }
    });
</script>
</body>
</html>
View Code

2.2.index.py(跳轉界面)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<h1>這是index界面</h1>
</body>
</html>
View Code

2.3.urls.py(部署路徑)

"""BBS URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
    path('login/', views.login),
    path('index/', views.index),
    # 極驗滑動驗證碼,獲取驗證碼的url
    path('pc-geetest/register/', views.get_geetest),
]
View Code

2.4.views.py

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

# Create your views here.
# 使用極驗滑動驗證碼的登錄功能
def login(request):
    # if request.is_ajax():  # 如果是AJAX請求
    if request.method == "POST":
        # 初始化一個給AJAX返回的數據
        ret = {"status": 0, "msg": ""}
        # 從提交過來的數據中 取到用戶名和密碼
        username = request.POST.get("username")
        pwd = request.POST.get("password")
        # 獲取極驗 滑動驗證碼相關的參數
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.POST.get(gt.FN_CHALLENGE, '')
        validate = request.POST.get(gt.FN_VALIDATE, '')
        seccode = request.POST.get(gt.FN_SECCODE, '')
        status = request.session[gt.GT_STATUS_SESSION_KEY]
        user_id = request.session["user_id"]

        if status:
            result = gt.success_validate(challenge, validate, seccode, user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)
        if result:
            # 驗證碼正確
            # 利用auth模塊做用戶名和密碼的校驗
            user = auth.authenticate(username=username, password=pwd)
            if user:
                # 用戶名密碼正確
                # 給用戶做登錄
                auth.login(request, user)
                ret["msg"] = "/index/"
            else:
                # 用戶名密碼錯誤
                ret["status"] = 1
                ret["msg"] = "用戶名或密碼錯誤!"
        else:
            ret["status"] = 1
            ret["msg"] = "驗證碼錯誤"

        return JsonResponse(ret)
    return render(request, "login.html")

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

# 處理極驗驗證碼的試視圖
#請在官網申請ID使用,示例ID不可使用
pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"
def get_geetest(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 HttpResponse(response_str)
View Code

2.5.settings.py

  settings.py需要加一些東西。首先創建一個數據庫,用於存儲各類表。創建好之后,需要連接pycharm。

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bbs',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '000000',
    }
}
修改setting.py中的這一部分

  同時在項目下的app目錄中的__init__.py中加上兩行代碼,告訴pychram我用了mysql。

import pymysql
pymysql.install_as_MySQLdb()
View Code

  在settings.py的最下方加上:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

2.6.生成用戶

  終端執行兩行代碼:

python manage.py makemigrations
python manage.py migrate

  在auth_user表中添加一個用戶,超級用戶和普通用戶都可以。

python manage.py createsuperuser

3.靜態文件

https://files.cnblogs.com/files/missdx/static.rar

4.效果圖

5.項目目錄結構圖

 


免責聲明!

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



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