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 第一步 hello world
Sep 25 Python
python 从远程服务器下载日志文件的程序
Feb 10 Python
Python 检查数组元素是否存在类似PHP isset()方法
Oct 14 Python
Python的gevent框架的入门教程
Apr 29 Python
深入了解Python中pop和remove的使用方法
Jan 09 Python
python PrettyTable模块的安装与简单应用
Jan 11 Python
python selenium执行所有测试用例并生成报告的方法
Feb 13 Python
详解python 爬取12306验证码
May 10 Python
windows上安装python3教程以及环境变量配置详解
Jul 18 Python
python扫描线填充算法详解
Feb 19 Python
python print 格式化输出,动态指定长度的实现
Apr 12 Python
python Matplotlib数据可视化(1):简单入门
Sep 30 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无限级分类方法及代码
2013/06/21 PHP
PHP的password_hash()使用实例
2014/03/17 PHP
分享下php5类中三种数据类型的区别
2015/01/26 PHP
一个非常完美的读写ini格式的PHP配置类分享
2015/02/12 PHP
对laravel的session获取与存取方法详解
2019/10/08 PHP
asp.net+js 实现无刷新上传解析csv文件的代码
2010/05/17 Javascript
JS代码防止SQL注入的方法(超简单)
2016/04/12 Javascript
浅谈JavaScript函数的四种存在形态
2016/06/08 Javascript
jQuery File Upload文件上传插件使用详解
2016/12/06 Javascript
Angular路由简单学习
2016/12/26 Javascript
微信小程序实现张图片合成为一张并下载
2019/07/16 Javascript
Js参数RSA加密传输之jsencrypt.js的使用
2020/02/07 Javascript
小程序实现密码输入框
2020/11/16 Javascript
[00:33]2018DOTA2亚洲邀请赛TNC出场
2018/04/04 DOTA
python进阶教程之词典、字典、dict
2014/08/29 Python
Python编写电话薄实现增删改查功能
2016/05/07 Python
浅谈五大Python Web框架
2017/03/20 Python
python利用lxml读写xml格式的文件
2017/08/10 Python
python中os.remove()用法及注意事项
2021/01/31 Python
FORZIERI澳大利亚站:全球顶级奢华配饰精品店
2016/12/31 全球购物
美国面料纺织品商城:Fabric.com
2017/06/28 全球购物
意大利奢侈品购物网站:Deliberti
2019/10/08 全球购物
美国一家著名的手表在线折扣网站:Discount Watch Store
2020/02/24 全球购物
成都思必达公司C#程序员招聘面试题
2013/06/26 面试题
项目专员岗位职责
2013/12/04 职场文书
平民服装店创业计划书
2014/01/17 职场文书
会计学专业学生的求职信范文
2014/01/27 职场文书
小学校园活动策划
2014/01/30 职场文书
给老婆的检讨书
2015/01/27 职场文书
小学元宵节活动总结
2015/02/06 职场文书
八年级作文之感悟亲情
2019/11/20 职场文书
Go语言基础知识点介绍
2021/07/04 Golang
python字典进行运算原理及实例分享
2021/08/02 Python
Python 如何利用ffmpeg 处理视频素材
2021/11/27 Python
flex布局中使用flex-wrap实现换行的项目实践
2022/06/21 HTML / CSS
TaiShan 200服务器安装Ubuntu 18.04的图文教程
2022/06/28 Servers