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

前端部分
隨便選擇一個(gè)(最下面的是移動(dòng)端,不做移動(dòng)端不要選)把html和js代碼復(fù)制過來,我選擇的是彈出式的。這里面要注意他的ajax請(qǐng)求發(fā)送的網(wǎng)址,你可以把這個(gè)網(wǎng)址改成自己視圖函數(shù)對(duì)應(yīng)的網(wǎng)址,自己寫里面的邏輯,比如我是為了做用戶登陸驗(yàn)證,所以我是寫的邏輯是拿用戶輸入的賬號(hào)、密碼和數(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">注冊(cè)</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)行二次驗(yà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();
});
// 將驗(yàn)證碼加到id為captcha的元素里
captchaObj.appendTo("#popup-captcha");
// 更多接口參考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
// 驗(yàn)證開始需要向網(wǎng)站主后臺(tái)獲取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)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它做appendTo之類的事件
initGeetest({
gt: data.gt,
challenge: data.challenge,
product: "popup", // 產(chǎn)品形式,包括:float,embed,popup。注意只對(duì)PC版驗(yàn)證碼有效
offline: !data.success // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī),一般不需要關(guān)注
// 更多配置參數(shù)請(qǐng)參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handlerPopup);
}
});
注意:我是把a(bǔ)jax請(qǐng)求的url改成了當(dāng)前頁面的視圖函數(shù)。另外原生代碼是全部寫在html里的,我把它做了解耦。還有原生代碼用的是jquery-1.12.3,我改成了jquery-3.3.1,也可以正常使用。
后端部分
urls.py
由于后端的邏輯是自己寫的,這里只需要用到pcgetcaptcha這部分代碼,來處理驗(yàn)證部分。
首先在urls.py里加入路徑
from django.urls import path, re_path
from blog.views import slide_code_auth
# 滑動(dòng)驗(yàn)證碼
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不可省略,如果做移動(dòng)端要加上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'] = '用戶名或密碼錯(cuò)誤'
return JsonResponse(response)
return render(request, 'login.html')
# 滑動(dòng)驗(yàn)證碼
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)代碼,把滑動(dòng)驗(yàn)證用到注冊(cè)頁面**
register.js
// 頭像預(yù)覽功能
$('#id_avatar').change(function () { // 圖片發(fā)生了變化,所以要用change事件
// 獲取用戶選中的文件對(duì)象
let file_obj = $(this)[0].files[0];
// 獲取文件對(duì)象的路徑
let reader = new FileReader(); // 等同于在python里拿到了實(shí)例對(duì)象
reader.readAsDataURL(file_obj);
reader.onload = function () {
// 修改img的src屬性,src = 文件對(duì)象的路徑
$("#avatar_img").attr('src', reader.result); // 這個(gè)是異步,速度比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里實(shí)例化一個(gè)對(duì)象
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) {
// 注冊(cè)成功
location.href = '/login/'
} else {
// 注冊(cè)失敗
// 清空錯(cuò)誤信息,每次展示錯(cuò)誤信息前,先把之前的清空了。
$('span.error-info').html("");
$('.form-group').removeClass('has-error');
// 展示此次提交的錯(cuò)誤信息
$.each(data.msg, function (field, error_list) {
if (field === '__all__') { // 全局錯(cuò)誤信息,在全局鉤子里自己定義的
$('#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();
});
// 將驗(yàn)證碼加到id為captcha的元素里
captchaObj.appendTo("#popup-captcha");
// 更多接口參考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
// 驗(yàn)證開始需要向網(wǎng)站主后臺(tái)獲取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)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它做appendTo之類的事件
initGeetest({
gt: data.gt,
challenge: data.challenge,
product: "popup", // 產(chǎn)品形式,包括:float,embed,popup。注意只對(duì)PC版驗(yàn)證碼有效
offline: !data.success // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī),一般不需要關(guān)注
// 更多配置參數(shù)請(qǐng)參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handlerPopup);
}
});
views.py
根據(jù)需求自己寫邏輯
總結(jié):滑動(dòng)驗(yàn)證主要用到的是js部分,只需修改ajax里傳遞的值就好,后臺(tái)邏輯自己寫。
以上所述是小編給大家介紹的使用python實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
- Python實(shí)現(xiàn)新版正方系統(tǒng)滑動(dòng)驗(yàn)證碼識(shí)別
- python自動(dòng)化操作之動(dòng)態(tài)驗(yàn)證碼、滑動(dòng)驗(yàn)證碼的降噪和識(shí)別
- Python 200行代碼實(shí)現(xiàn)一個(gè)滑動(dòng)驗(yàn)證碼過程詳解
- python驗(yàn)證碼識(shí)別教程之滑動(dòng)驗(yàn)證碼
- Python破解極驗(yàn)滑動(dòng)驗(yàn)證碼詳細(xì)步驟
- 用Python爬蟲破解滑動(dòng)驗(yàn)證碼的案例解析
- 基于python實(shí)現(xiàn)破解滑動(dòng)驗(yàn)證碼過程解析
- python破解bilibili滑動(dòng)驗(yàn)證碼登錄功能
- python自動(dòng)化測(cè)試之破解滑動(dòng)驗(yàn)證碼
相關(guān)文章
python使用xmlrpclib模塊實(shí)現(xiàn)對(duì)百度google的ping功能
這篇文章主要介紹了python使用xmlrpclib模塊實(shí)現(xiàn)對(duì)百度google的ping功能,實(shí)例分析了xmlrpclib模塊的相關(guān)技巧,需要的朋友可以參考下2015-06-06
python和websocket構(gòu)建實(shí)時(shí)日志跟蹤器的步驟
這篇文章主要介紹了python和websocket構(gòu)建實(shí)時(shí)日志跟蹤器的步驟,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04
使用python進(jìn)行文本預(yù)處理和提取特征的實(shí)例
今天小編就為大家分享一篇使用python進(jìn)行文本預(yù)處理和提取特征的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06
基于Python實(shí)現(xiàn)一鍵找出磁盤里所有貓照
最近在整理我磁盤上的照片,發(fā)現(xiàn)不少貓照,突然覺得若能把這些貓照都挑出來,觀察它們的成長軌跡也是一件不錯(cuò)的事情。一張一張的找實(shí)在是太費(fèi)勁了,能不能自動(dòng)化地找出來呢?本文將詳細(xì)為大家講講,需要的可以參考一下2022-05-05

