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登陆asp网站页面的实现代码
Jan 14 Python
Python的Django中将文件上传至七牛云存储的代码分享
Jun 03 Python
Python利用operator模块实现对象的多级排序详解
May 09 Python
pandas修改DataFrame列名的方法
Apr 08 Python
django允许外部访问的实例讲解
May 14 Python
python实现多进程代码示例
Oct 31 Python
Python解析json时提示“string indices must be integers”问题解决方法
Jul 31 Python
python绘制动态曲线教程
Feb 24 Python
python 多线程死锁问题的解决方案
Aug 25 Python
使用Python获取爱奇艺电视剧弹幕数据的示例代码
Jan 12 Python
python基于selenium爬取斗鱼弹幕
Feb 20 Python
Python .py生成.pyd文件并打包.exe 的注意事项说明
Mar 04 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删除HTMl标签的三种解决方法
2013/06/30 PHP
php 在线导入mysql大数据程序
2015/06/11 PHP
如何解决phpmyadmin导入数据库文件最大限制2048KB
2015/10/09 PHP
Thinkphp5框架简单实现钩子(Hook)行为的方法示例
2019/09/03 PHP
php实现通过stomp协议连接ActiveMQ操作示例
2020/02/23 PHP
TP5框架安全机制实例分析
2020/04/05 PHP
用Javascript实现锚点(Anchor)间平滑跳转
2009/09/08 Javascript
使用jQuery实现dropdownlist的联动效果(sharepoint 2007)
2011/03/30 Javascript
firefox下jQuery UI Autocomplete 1.8.*中文输入修正方法
2012/09/19 Javascript
解析Javascript中难以理解的11个问题
2013/12/09 Javascript
jquery+php随机生成红包金额数量代码分享
2015/08/27 Javascript
jQuery+CSS3+Html5实现弹出层效果实例代码(附源码下载)
2016/05/16 Javascript
jquery ajax结合thinkphp的getjson实现跨域的方法
2016/06/06 Javascript
利用js来实现缩略语列表、文献来源链接和快捷键列表
2016/12/16 Javascript
详解vue.js的devtools安装
2017/05/26 Javascript
基于vue.js实现的分页
2018/03/13 Javascript
详解Vue微信授权登录前后端分离较为优雅的解决方案
2018/06/29 Javascript
JavaScript数组方法的错误使用例子
2018/09/13 Javascript
js实现搜索栏效果
2018/11/16 Javascript
基于mpvue搭建微信小程序项目框架的教程详解
2019/04/10 Javascript
vue2 v-model/v-text 中使用过滤器的方法示例
2019/05/09 Javascript
Bootstrap table 实现树形表格联动选中联动取消功能
2019/09/30 Javascript
[01:21]DOTA2 新英雄 森海飞霞
2020/12/18 DOTA
Python中获取网页状态码的两个方法
2014/11/03 Python
Python实现的Excel文件读写类
2015/07/30 Python
Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
2018/03/19 Python
Python检查和同步本地时间(北京时间)的实现方法
2018/12/03 Python
对pyqt5中QTabWidget的相关操作详解
2019/06/21 Python
利用CSS3实现动态的二级三级菜单效果实例源码
2017/01/04 HTML / CSS
Html5之webcoekt播放JPEG图片流
2020/09/22 HTML / CSS
酒店led欢迎词
2014/01/09 职场文书
自立自强的名人事例
2014/02/10 职场文书
物业品质提升方案
2014/06/08 职场文书
活动经费申请报告
2015/05/15 职场文书
2015年网络管理员工作总结
2015/05/21 职场文书
Go gorilla/sessions库安装使用
2022/08/14 Golang