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查找第k小元素代码分享
Dec 18 Python
Python读取环境变量的方法和自定义类分享
Nov 22 Python
python多进程和多线程究竟谁更快(详解)
May 29 Python
Django Admin 实现外键过滤的方法
Sep 29 Python
对python使用http、https代理的实例讲解
May 07 Python
Python实现决策树C4.5算法的示例
May 30 Python
Python中几种属性访问的区别与用法详解
Oct 10 Python
python定时检测无响应进程并重启的实例代码
Apr 22 Python
对pyqt5之menu和action的使用详解
Jun 20 Python
python实现处理mysql结果输出方式
Apr 09 Python
Django web自定义通用权限控制实现方法
Nov 24 Python
python神经网络ResNet50模型
May 06 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
Mysql的常用命令
2006/10/09 PHP
第二节--PHP5 的对象模型
2006/11/16 PHP
PHP取得一个类的属性和方法的实现代码
2011/05/22 PHP
ThinkPHP CURD方法之table方法详解
2014/06/18 PHP
ThinkPHP实例化模型的四种方法概述
2014/08/22 PHP
laravel安装和配置教程
2014/10/29 PHP
php常用hash加密函数
2014/11/22 PHP
laravel配置Redis多个库的实现方法
2019/04/10 PHP
关于javascript DOM事件模型的两件事
2010/07/22 Javascript
js 判断checkbox是否选中的实现代码
2010/11/23 Javascript
js下关于onmouseout、事件冒泡的问题经验小结
2010/12/09 Javascript
jQuery 选择器项目实例分析及实现代码
2012/12/28 Javascript
jquery实现智能感知连接外网搜索
2013/05/21 Javascript
nodejs教程之入门
2014/11/21 NodeJs
javascript中Math.random()使用详解
2015/04/15 Javascript
JavaScript中将数组进行合并的基本方法讲解
2016/03/07 Javascript
Javascript实现苹果悬浮虚拟按钮
2016/04/10 Javascript
Html5+jQuery+CSS制作相册小记录
2016/12/30 Javascript
Vue2.0利用 v-model 实现组件props双向绑定的优美解决方案
2017/03/13 Javascript
vuex 项目结构目录及一些简单配置介绍
2018/04/08 Javascript
webpack打包nodejs项目的方法
2018/09/26 NodeJs
vue 实现tab切换保持数据状态
2020/07/21 Javascript
python 正则式 概述及常用字符
2009/05/07 Python
Python实现屏幕截图的代码及函数详解
2016/10/01 Python
在python中pandas的series合并方法
2018/11/12 Python
Django将默认的SQLite更换为MySQL的实现
2019/11/18 Python
Python3.7基于hashlib和Crypto实现加签验签功能(实例代码)
2019/12/04 Python
基于python实现生成指定大小txt文档
2020/07/20 Python
为什么要优先使用同步代码块而不是同步方法?
2013/01/30 面试题
环境工程大学生自荐信
2013/10/21 职场文书
会议开场欢迎词
2014/01/15 职场文书
大学竞选班长演讲稿
2014/04/24 职场文书
2014年教师学期工作总结
2014/11/08 职场文书
幼儿园教师自荐书
2015/03/06 职场文书
公司市场部岗位职责
2015/04/15 职场文书
特别篇动画《总之就是非常可爱 ~制服~》PV公开,2022年夏季播出
2022/04/04 日漫