Django-simple-captcha验证码包使用方法详解


Posted in Python onNovember 28, 2020

django-simple-captcha是django的验证码包,非常简单实用,这次记录的是如何点击验证码后刷新验证码,因为这个功能官方文档并没有详细给出。

django-simple-captcha官方文档:http://django-simple-captcha.readthedocs.io/en/latest/

django-simple-captcha的github网址:https://github.com/mbi/django-simple-captcha

开始

1.安装 pip install django-simple-captcha, pip install Pillow

2.将captcha 加入 settings.py 的 INSTALLED_APPS

3.运行 python manage.py makemigrations 和 python manage.py migrate

4.url路由加入urls.py的urlpatterns

urlpatterns = [
  path('captcha/', include('captcha.urls')),    # 图片验证码 路由
  path('refresh_captcha/', views.refresh_captcha),  # 刷新验证码,ajax
  path('test/',IndexView.as_view()),         #get与post请求路径
]

5.在views.py中加入以下代码

from django.shortcuts import render
from django.views.generic import View
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
from django.http import HttpResponse
import json


# 创建验证码
def captcha():
  hashkey = CaptchaStore.generate_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 = CaptchaStore.objects.get(hashkey=captchaHashkey)
      if get_captcha.response == captchaStr.lower(): # 如果验证码匹配
        return True
    except:
      return False
  else:
    return False


class IndexView(View):
  def get(self, request):
    hashkey = CaptchaStore.generate_key() # 验证码答案
    image_url = captcha_image_url(hashkey) # 验证码地址
    print(hashkey,image_url)
    captcha = {'hashkey': hashkey, 'image_url': image_url}
    return render(request, "login.html", locals())

  def post(self, request):
    capt = request.POST.get("captcha", None) # 用户提交的验证码
    key = request.POST.get("hashkey", None) # 验证码答案
    if jarge_captcha(capt, key):
      return HttpResponse("验证码正确")
    else:
      return HttpResponse("验证码错误")

6.templates文件夹下login.html的内容

{% load static %}
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.0.0/js/bootstrap.js"></script>
</head>
<body>
  <form action="/test/" method="post">
    {% csrf_token %}
    <a href="#" rel="external nofollow" 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>
    <!-- 动态刷新验证码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>

django-simple-captcha并没有使用session对验证码进行存储,而是使用了数据库,当你在做数据库迁移的时候会生成一个表 captcha_captchastore ,包含以下字段

challenge = models.CharField(blank=False, max_length=32) # 验证码大写或者数学计算比如 1+1
response = models.CharField(blank=False, max_length=32) # 需要输入的验证码 验证码小写或数学计算的结果 比如 2
hashkey = models.CharField(blank=False, max_length=40, unique=True) # hash值
expiration = models.DateTimeField(blank=False) # 到期时间

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
跟老齐学Python之玩转字符串(2)更新篇
Sep 28 Python
Python中使用Queue和Condition进行线程同步的方法
Jan 19 Python
Python父目录、子目录的相互调用方法
Feb 16 Python
selenium跳过webdriver检测并模拟登录淘宝
Jun 12 Python
对pyqt5中QTabWidget的相关操作详解
Jun 21 Python
wxPython实现分隔窗口
Nov 19 Python
TensorFlow实现指数衰减学习率的方法
Feb 05 Python
Scrapy框架实现的登录网站操作示例
Feb 06 Python
python对XML文件的操作实现代码
Mar 27 Python
基于python计算并显示日间、星期客流高峰
May 07 Python
Pycharm同步远程服务器调试的方法步骤
Nov 04 Python
python实现会员管理系统
Mar 18 Python
如何通过Python实现RabbitMQ延迟队列
Nov 28 #Python
python 用Matplotlib作图中有多个Y轴
Nov 28 #Python
基于python实现监听Rabbitmq系统日志代码示例
Nov 28 #Python
Python Http请求json解析库用法解析
Nov 28 #Python
基于Django集成CAS实现流程详解
Nov 28 #Python
Django haystack实现全文搜索代码示例
Nov 28 #Python
windows下python 3.9 Numpy scipy和matlabplot的安装教程详解
Nov 28 #Python
You might like
PHP array 的加法操作代码
2010/07/24 PHP
php计算程序运行时间的简单例子分享
2014/05/10 PHP
PHP中使用CURL获取页面title例子
2015/01/07 PHP
php获取'/'传参的值简单方法
2017/07/13 PHP
iframe如何动态创建及释放其所占内存
2014/09/03 Javascript
jQuery使用post方法提交数据实例
2015/03/25 Javascript
通过实例理解javascript中没有函数重载的概念
2015/06/03 Javascript
Vue组件开发初探
2017/02/14 Javascript
clipboard.js在移动端复制失败的解决方法
2018/06/13 Javascript
js中数组常用方法总结(推荐)
2019/04/09 Javascript
使用C语言扩展Python程序的简单入门指引
2015/04/14 Python
python实现将汉字转换成汉语拼音的库
2015/05/05 Python
Python入门之三角函数atan2()函数详解
2017/11/08 Python
git进行版本控制心得详谈
2017/12/10 Python
Python爬取商家联系电话以及各种数据的方法
2018/11/10 Python
python实现大转盘抽奖效果
2019/01/22 Python
python实现H2O中的随机森林算法介绍及其项目实战
2019/08/29 Python
Python读取表格类型文件代码实例
2020/02/17 Python
Jupyter notebook 启动闪退问题的解决
2020/04/13 Python
python中PyQuery库用法分享
2021/01/15 Python
Python 的 f-string 可以连接字符串与数字的原因解析
2021/02/20 Python
CSS中几个与换行有关的属性简明总结
2014/04/15 HTML / CSS
用HTML5 Canvas API中的clearRect()方法实现橡皮擦功能
2016/03/15 HTML / CSS
html5 input输入实时检测以及延时优化
2018/07/18 HTML / CSS
Emma Bridgewater官网:英国餐具制造商
2019/11/24 全球购物
澳大利亚在线床零售商:Bedworks
2020/09/01 全球购物
大学生应聘推荐信范文
2013/11/19 职场文书
工作人员思想汇报
2014/01/09 职场文书
教师旷工检讨书
2014/01/18 职场文书
同学聚会主持词
2014/03/18 职场文书
党支部2014年度工作总结
2014/12/04 职场文书
大连星海广场导游词
2015/02/10 职场文书
总经理岗位职责范本
2015/04/01 职场文书
用Python将库打包发布到pypi
2021/04/13 Python
用Python的绘图库(matplotlib)绘制小波能量谱
2021/04/17 Python
使用 CSS 构建强大且酷炫的粒子动画效果
2022/08/14 HTML / CSS