Django中图形验证码(django-simple-captcha)django-simple-captcha
在⽹站开发的登录页⾯中,经常会需要使⽤到图形验证码来验证。在Django中,django-simple-captcha库包提供了图形验证码的使⽤。下⾯我们来讲讲如何使⽤django-simple-captcha包来图形验证,并且点击图⽚刷新验证码。
django-simple-captcha的安装
pip install django-simple-captcha
在settings.py⽂件中注册captcha
INSTALLED_APPS = [
'captcha'
]
在settings.py⽂件中设置图形验证码的样式
#字母验证码
CAPTCHA_IMAGE_SIZE = (80, 45)  # 设置 captcha 图⽚⼤⼩
CAPTCHA_LENGTH = 4  # 字符个数
CAPTCHA_TIMEOUT = 1  # 超时(minutes)
#加减乘除验证码
CAPTCHA_OUTPUT_FORMAT = '%(image)s %(text_field)s %(hidden_field)s '
CAPTCHA_NOISE_FUNCTIONS = ('ise_null',
'ise_arcs', # 线
'ise_dots', # 点
)
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge'
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
CAPTCHA_TIMEOUT = 1
执⾏数据迁移,在数据表中⽣成captcha_captchastore表
python manage.py migrate
在urls.py中添加路由
urlpatterns = [
path('captcha/', include('captcha.urls')),      # 图⽚验证码路由
path('refresh_captcha/', fresh_captcha),    # 刷新验证码,ajax
]
下⾯是源代码。
urls.py⽂件
from django.urls import path
f.urls import include
from App.views import IndexView
from App import views
urlpatterns = [
path('captcha/', include('captcha.urls')),
path('refresh_captcha/',fresh_captcha),
path('',IndexView.as_view()),
]
views.py⽂件
from django.shortcuts import render
from ic import View
dels import CaptchaStore
from captcha.helpers import  captcha_image_url
from django.http import HttpResponse
import json
# 创建验证码
def captcha():
hashkey = ate_key()  #验证码答案
image_url = captcha_image_url(hashkey)  #验证码地址
captcha = {'hashkey': hashkey, 'image_url': image_url}
return captcha
#刷新验证码
def refresh_captcha(request):
return HttpResponse(json.dumps(captcha()), content_type='application/json')
# 验证验证码
def jarge_captcha(captchaStr, captchaHashkey):
if captchaStr and captchaHashkey:
try:
# 获取根据hashkey获取数据库中的response值
get_captcha = (hashkey=captchaHashkey)
if sponse == captchaStr.lower():    # 如果验证码匹配
return True
except:
return False
else:
return False
class IndexView(View):
def get(self, request):
hashkey = ate_key()  # 验证码答案
image_url = captcha_image_url(hashkey)  # 验证码地址
captcha = {'hashkey': hashkey, 'image_url': image_url}
return render(request, "login.html", locals())
def post(self,request):
capt=("captcha",None)        #⽤户提交的验证码
key=("hashkey",None)          #验证码答案
if jarge_captcha(capt,key):
return  HttpResponse("验证码正确")
else:
return HttpResponse("验证码错误")
login.html⽂件,这⾥使⽤ js 动态刷新图形验证码⽤到了jquery和bootstrap的js,所以,我们提前将jquery和bootstrap放在了static⽂件夹下。关于如何加载静态⽂件,传送门——>
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{% static 'bower_components/jquery/dist/jquery.min.js' %}"></script>
<script src="{% static 'bower_components/bootstrap/dist/js/bootstrap.min.js'%}"></script>
</head>
<body>
<form action="/" method="post">
<a href="#" class="captcha">
<img src="{{ captcha.image_url }}" alt="点击切换" id="id_captcha" >
</a> <br>
<input type="text" name="captcha" placeholder="验证码"> <br>
<input value="{{ captcha.hashkey }}" name="hashkey" type="hidden" id="id_captcha_0">
<button type="submit" class="btn btn-primary btn-block ">提交</button>
</form>
<script>django登录注册功能
<!-- 动态刷新验证码js -->
$(document).ready(function(){
$('.captcha').click(function () {
$.getJSON("refresh_captcha/", function (result) {
$('#id_captcha').attr('src', result['image_url']);
$('#id_captcha_0').val(result['hashkey'])
});
});
});
</script>
</body>
</html>
参考⽂章:
本⽂所有代码:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。