使用python實現(xiàn)滑動驗證碼功能
首先安裝一個需要用到的模塊
pip install social-auth-app-django
安裝完后在終端輸入pip list會看到
social-auth-app-django 3.1.0 social-auth-core 3.0.0
然后可以來我的github,下載關(guān)于滑動驗證碼的這個demo:https://github.com/Edward66/slide_auth_code
下載完后啟動項目
python manage.py runserver
啟動這個項目后,在主頁就能看到示例

前端部分
隨便選擇一個(最下面的是移動端,不做移動端不要選)把html和js代碼復(fù)制過來,我選擇的是彈出式的。這里面要注意他的ajax請求發(fā)送的網(wǎng)址,你可以把這個網(wǎng)址改成自己視圖函數(shù)對應(yīng)的網(wǎng)址,自己寫里面的邏輯,比如我是為了做用戶登陸驗證,所以我是寫的邏輯是拿用戶輸入的賬號、密碼和數(shù)據(jù)庫里的做匹配。
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" rel="external nofollow" >
<link rel="stylesheet" href="/static/blog/bs/css/bootstrap.css" rel="external nofollow" >
</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' %}" rel="external nofollow" 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) {
// 成功的回調(diào)
captchaObj.onSuccess(function () {
let validate = captchaObj.getValidate();
$.ajax({
url: "", // 進(jìn)行二次驗證
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
};
// 驗證開始需要向網(wǎng)站主后臺獲取id,challenge,success(是否啟用failback)
$.ajax({
url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存
type: "get",
dataType: "json",
success: function (data) {
// 使用initGeetest接口
// 參數(shù)1:配置參數(shù)
// 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它做appendTo之類的事件
initGeetest({
gt: data.gt,
challenge: data.challenge,
product: "popup", // 產(chǎn)品形式,包括:float,embed,popup。注意只對PC版驗證碼有效
offline: !data.success // 表示用戶后臺檢測極驗服務(wù)器是否宕機(jī),一般不需要關(guān)注
// 更多配置參數(shù)請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handlerPopup);
}
});
注意:我是把a(bǔ)jax請求的url改成了當(dāng)前頁面的視圖函數(shù)。另外原生代碼是全部寫在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里面,當(dāng)做工具使用
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')
注意:不一定非要按照我這樣,根據(jù)自己的需求選擇相應(yīng)的功能并做出相應(yīng)的修改
**修改相應(yīng)代碼,把滑動驗證用到注冊頁面**
register.js
// 頭像預(yù)覽功能
$('#id_avatar').change(function () { // 圖片發(fā)生了變化,所以要用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加載完后在執(zhí)行。
};
});
// 基于Ajax提交數(shù)據(jù)
let handlerPopup = function (captchaObj) {
// 成功的回調(diào)
captchaObj.onSuccess(function () {
let validate = captchaObj.getValidate();
let formdata = new FormData(); // 相當(dāng)于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
};
// 驗證開始需要向網(wǎng)站主后臺獲取id,challenge,success(是否啟用failback)
$.ajax({
url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存
type: "get",
dataType: "json",
success: function (data) {
// 使用initGeetest接口
// 參數(shù)1:配置參數(shù)
// 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它做appendTo之類的事件
initGeetest({
gt: data.gt,
challenge: data.challenge,
product: "popup", // 產(chǎn)品形式,包括:float,embed,popup。注意只對PC版驗證碼有效
offline: !data.success // 表示用戶后臺檢測極驗服務(wù)器是否宕機(jī),一般不需要關(guān)注
// 更多配置參數(shù)請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handlerPopup);
}
});
views.py
根據(jù)需求自己寫邏輯
總結(jié):滑動驗證主要用到的是js部分,只需修改ajax里傳遞的值就好,后臺邏輯自己寫。
以上所述是小編給大家介紹的使用python實現(xiàn)滑動驗證碼功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
python使用xmlrpclib模塊實現(xiàn)對百度google的ping功能
這篇文章主要介紹了python使用xmlrpclib模塊實現(xiàn)對百度google的ping功能,實例分析了xmlrpclib模塊的相關(guān)技巧,需要的朋友可以參考下2015-06-06
python和websocket構(gòu)建實時日志跟蹤器的步驟
這篇文章主要介紹了python和websocket構(gòu)建實時日志跟蹤器的步驟,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04
使用python進(jìn)行文本預(yù)處理和提取特征的實例
今天小編就為大家分享一篇使用python進(jìn)行文本預(yù)處理和提取特征的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06

