当前位置:   article > 正文

Django中图形验证码(django-simple-captcha)

django-simple-captcha

django-simple-captcha

在网站开发的登录页面中,经常会需要使用到图形验证码来验证。在Django中,django-simple-captcha库包提供了图形验证码的使用。

下面我们来讲讲如何使用django-simple-captcha包来图形验证,并且点击图片刷新验证码。

django-simple-captcha的安装

pip install django-simple-captcha

在settings.py文件中注册captcha

  1. INSTALLED_APPS = [
  2. 'captcha'
  3. ]

在settings.py文件中设置图形验证码的样式

  1. #字母验证码
  2. CAPTCHA_IMAGE_SIZE = (80, 45) # 设置 captcha 图片大小
  3. CAPTCHA_LENGTH = 4 # 字符个数
  4. CAPTCHA_TIMEOUT = 1 # 超时(minutes)
  5. #加减乘除验证码
  6. CAPTCHA_OUTPUT_FORMAT = '%(image)s %(text_field)s %(hidden_field)s '
  7. CAPTCHA_NOISE_FUNCTIONS = ('captcha.helpers.noise_null',
  8. 'captcha.helpers.noise_arcs', # 线
  9. 'captcha.helpers.noise_dots', # 点
  10. )
  11. CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge'
  12. CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
  13. CAPTCHA_TIMEOUT = 1
'
运行

执行数据迁移,在数据表中生成captcha_captchastore表

python manage.py migrate

在urls.py中添加路由

  1. urlpatterns = [
  2. path('captcha/', include('captcha.urls')), # 图片验证码 路由
  3. path('refresh_captcha/', views.refresh_captcha), # 刷新验证码,ajax
  4. ]

下面是源代码。 

urls.py文件

  1. from django.urls import path
  2. from django.conf.urls import include
  3. from App.views import IndexView
  4. from App import views
  5. urlpatterns = [
  6. path('captcha/', include('captcha.urls')),
  7. path('refresh_captcha/',views.refresh_captcha),
  8. path('',IndexView.as_view()),
  9. ]

views.py文件

  1. from django.shortcuts import render
  2. from django.views.generic import View
  3. from captcha.models import CaptchaStore
  4. from captcha.helpers import captcha_image_url
  5. from django.http import HttpResponse
  6. import json
  7. # 创建验证码
  8. def captcha():
  9. hashkey = CaptchaStore.generate_key() #验证码答案
  10. image_url = captcha_image_url(hashkey) #验证码地址
  11. captcha = {'hashkey': hashkey, 'image_url': image_url}
  12. return captcha
  13. #刷新验证码
  14. def refresh_captcha(request):
  15. return HttpResponse(json.dumps(captcha()), content_type='application/json')
  16. # 验证验证码
  17. def jarge_captcha(captchaStr, captchaHashkey):
  18. if captchaStr and captchaHashkey:
  19. try:
  20. # 获取根据hashkey获取数据库中的response值
  21. get_captcha = CaptchaStore.objects.get(hashkey=captchaHashkey)
  22. if get_captcha.response == captchaStr.lower(): # 如果验证码匹配
  23. return True
  24. except:
  25. return False
  26. else:
  27. return False
  28. class IndexView(View):
  29. def get(self, request):
  30. hashkey = CaptchaStore.generate_key() # 验证码答案
  31. image_url = captcha_image_url(hashkey) # 验证码地址
  32. captcha = {'hashkey': hashkey, 'image_url': image_url}
  33. return render(request, "login.html", locals())
  34. def post(self,request):
  35. capt=request.POST.get("captcha",None) #用户提交的验证码
  36. key=request.POST.get("hashkey",None) #验证码答案
  37. if jarge_captcha(capt,key):
  38. return HttpResponse("验证码正确")
  39. else:
  40. return HttpResponse("验证码错误")

login.html文件,这里使用 js 动态刷新图形验证码用到了jquery和bootstrap的js,所以,我们提前将jquery和bootstrap放在了static文件夹下。关于如何加载静态文件,传送门——>Django加载静态文件

  1. {% load static %}
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>Title</title>
  7. <script src="{% static 'bower_components/jquery/dist/jquery.min.js' %}"></script>
  8. <script src="{% static 'bower_components/bootstrap/dist/js/bootstrap.min.js'%}"></script>
  9. </head>
  10. <body>
  11. <form action="/" method="post">
  12. <a href="#" class="captcha">
  13. <img src="{{ captcha.image_url }}" alt="点击切换" id="id_captcha" >
  14. </a> <br>
  15. <input type="text" name="captcha" placeholder="验证码"> <br>
  16. <input value="{{ captcha.hashkey }}" name="hashkey" type="hidden" id="id_captcha_0">
  17. <button type="submit" class="btn btn-primary btn-block ">提交</button>
  18. </form>
  19. <script>
  20. <!-- 动态刷新验证码js -->
  21. $(document).ready(function(){
  22. $('.captcha').click(function () {
  23. $.getJSON("refresh_captcha/", function (result) {
  24. $('#id_captcha').attr('src', result['image_url']);
  25. $('#id_captcha_0').val(result['hashkey'])
  26. });
  27. });
  28. });
  29. </script>
  30. </body>
  31. </html>

参考文章:https://blog.csdn.net/qq_37648632/article/details/83149803

本文所有代码:https://github.com/xie1997/Django_captcha

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/983037
推荐阅读
相关标签
  

闽ICP备14008679号