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 面向对象 成员的访问约束
Dec 23 Python
使用Python开发windows GUI程序入门实例
Oct 23 Python
python导出hive数据表的schema实例代码
Jan 22 Python
flask框架视图函数用法示例
Jul 19 Python
Python3爬虫学习入门教程
Dec 11 Python
Python Opencv实现图像轮廓识别功能
Mar 23 Python
python django下载大的csv文件实现方法分析
Jul 19 Python
在Django admin中编辑ManyToManyField的实现方法
Aug 09 Python
python做接口测试的必要性
Nov 20 Python
python生成并处理uuid的实现方式
Mar 03 Python
Pyecharts 动态地图 geo()和map()的安装与用法详解
Mar 25 Python
Django自关联实现多级联动查询实例
May 19 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
AM/FM收音机的安装与调试
2021/03/02 无线电
PHP学习笔记(三):数据类型转换与常量介绍
2015/04/17 PHP
PHP高并发和大流量解决方案整理
2019/12/24 PHP
js实现页面打印功能实例代码(附去页眉页脚功能代码)
2009/12/15 Javascript
jQuery中size()方法用法实例
2014/12/27 Javascript
jquery实现华丽的可折角广告代码
2015/09/02 Javascript
Angularjs中如何使用filterFilter函数过滤
2016/02/06 Javascript
JS JSOP跨域请求实例详解
2016/07/04 Javascript
JavaScript引用类型Object常见用法实例分析
2018/08/08 Javascript
学习React中ref的两个demo示例
2018/08/14 Javascript
解决vue2.0 element-ui中el-upload的before-upload方法返回false时submit()不生效问题
2018/08/24 Javascript
layui 图片上传+表单提交+ Spring MVC的实例
2019/09/21 Javascript
JavaScript中变量提升机制示例详解
2019/12/27 Javascript
[03:31]DOTA2英雄基础教程 大地之灵
2013/12/17 DOTA
对比Python中__getattr__和 __getattribute__获取属性的用法
2016/06/21 Python
Python中max函数用于二维列表的实例
2018/04/03 Python
Python使用pip安装pySerial串口通讯模块
2018/04/20 Python
Python实现确认字符串是否包含指定字符串的实例
2018/05/02 Python
python的中异常处理机制
2018/08/30 Python
pandas实现将dataframe满足某一条件的值选出
2019/06/12 Python
使用Python代码实现Linux中的ls遍历目录命令的实例代码
2019/09/07 Python
pycharm实现在虚拟环境中引入别人的项目
2020/03/09 Python
python读取mysql数据绘制条形图
2020/03/25 Python
通过Canvas及File API缩放并上传图片完整示例
2013/08/08 HTML / CSS
Html5 web本地存储实例详解
2016/07/28 HTML / CSS
linux面试题参考答案(9)
2016/01/29 面试题
JSF界面控制层技术
2013/06/17 面试题
人力资源专员自我评价怎么写
2013/09/19 职场文书
美丽家庭事迹材料
2014/05/03 职场文书
委托书格式
2014/08/01 职场文书
2015年实习生工作总结报告
2015/04/28 职场文书
离婚答辩状怎么写
2015/05/22 职场文书
公司2015年终工作总结
2015/05/26 职场文书
写作技巧:如何撰写一份优秀的营销策划书
2019/08/13 职场文书
Java使用JMeter进行高并发测试
2021/11/23 Java/Android
MySQL性能指标TPS+QPS+IOPS压测
2022/08/05 MySQL