首先安裝一個需要用到的模塊
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請求發(fā)送的網(wǎng)址,你可以把這個網(wǎng)址改成自己視圖函數(shù)對應的網(wǎng)址,自己寫里面的邏輯,比如我是為了做用戶登陸驗證,所以我是寫的邏輯是拿用戶輸入的賬號、密碼和數(shù)據(jù)庫里的做匹配。
login.html
登陸頁面
登陸頁面
login.js
let handlerPopup = function (captchaObj) {
// 成功的回調(diào)
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
};
// 驗證開始需要向網(wǎng)站主后臺獲取id,challenge,success(是否啟用failback)
$.ajax({
url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加隨機數(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 // 表示用戶后臺檢測極驗服務器是否宕機,一般不需要關注
// 更多配置參數(shù)請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handlerPopup);
}
});
注意:我是把ajax請求的url改成了當前頁面的視圖函數(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里面,當做工具使用
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ù)自己的需求選擇相應的功能并做出相應的修改
**修改相應代碼,把滑動驗證用到注冊頁面**
register.js
// 頭像預覽功能
$('#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(); // 相當于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(), // 加隨機數(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 // 表示用戶后臺檢測極驗服務器是否宕機,一般不需要關注
// 更多配置參數(shù)請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handlerPopup);
}
});
views.py
根據(jù)需求自己寫邏輯
總結:滑動驗證主要用到的是js部分,只需修改ajax里傳遞的值就好,后臺邏輯自己寫。
以上所述是小編給大家介紹的使用python實現(xiàn)滑動驗證碼功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

