一、自己生成验证码

二、极验科技互动验证码

使用前步骤:下载官网文件——pip install geetest——引入其封装的js模块

代码分为三段:生成验证码——显示验证码——验证验证码、

 from django.shortcuts import render,HttpResponse
 from django.http import JsonResponse
 from django.contrib import auth
 from geetest import GeetestLib

 # Create your views here.

 #使用极验滑动验证码的登陆
 def login(request):
     if request.method == "POST":
         ")
         #初始化一个返回给ajax的字典
         ret = {"status":0,"msg":""}
         #从提交的数据中获取用户名和密码
         username = request.POST.get("username")
         password = request.POST.get("password")
         #获取验证码相关数据
         gt = GeetestLib(pc_geetest_id, pc_geetest_key)
         challenge = request.POST.get(gt.FN_CHALLENGE, '')
         validate = request.POST.get(gt.FN_VALIDATE, '')
         seccode = request.POST.get(gt.FN_SECCODE, '')
         status = request.session[gt.GT_STATUS_SESSION_KEY]
         user_id = request.session["user_id"]

         if status:
             result = gt.success_validate(challenge, validate, seccode, user_id)
         else:
             result = gt.failback_validate(challenge, validate, seccode)

         #如果result有值,则验证成功,利用auth做验证
         if result:
             user = auth.authenticate(username=username,password=password)
             if user:
                 #如果用户名密码正确
                 auth.login(request,user)
                 ret["msg"] = "/index/"
             else:
                 ret["status"] = 1
                 ret["msg"] = "用户名密码错误"
         else:
             #如果验证吗错误
             ret["status"] = 1
             ret["msg"] = "验证码错误"
         return JsonResponse(ret)
     return render(request,"login.html",locals())

 #请在官网申请ID使用,示例ID不可使用
 pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
 pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"
 #获取滑动验证码
 def get_geetest(request):
     user_id = 'test'
     gt = GeetestLib(pc_geetest_id, pc_geetest_key)
     status = gt.pre_process(user_id)
     request.session[gt.GT_STATUS_SESSION_KEY] = status
     request.session["user_id"] = user_id
     response_str = gt.get_response_str()
     return HttpResponse(response_str)

 def index(request):
     return render(request,"index.html",locals())
 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>Title</title>
     <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
     <link rel="stylesheet" href="/static/css/mystyle.css">
 </head>
 <body>

 <div class="container">
     <div class="row">
         <form class="form-horizontal col-md-6 col-md-offset-3 login-form">
             {% csrf_token %}
             <div class="form-group">
                 <label for="username" class="col-sm-2 control-label">用户名</label>
                 <div class="col-sm-10">
                     <input type="text" class="form-control" id="username" name="username" placeholder="用户名">
                 </div>
             </div>
             <div class="form-group">
                 <label for="password" class="col-sm-2 control-label">密码</label>
                 <div class="col-sm-10">
                     <input type="password" class="form-control" id="password" name="password" placeholder="密码">
                 </div>
             </div>
             <div class="form-group">
                 <div id="popup-captcha"></div>
             </div>
             <div class="form-group">
                 <div class="col-sm-offset-2 col-sm-10">
                     <button type="button" class="btn btn-default" id="login-button">登录</button>
                     <span class="login-error"></span>
                 </div>
             </div>
         </form>
     </div>
 </div>

 <script src="/static/jquery.js"></script>
 <script src="/static/bootstrap/js/bootstrap.min.js"></script>
 <!-- 引入封装了failback的接口--initGeetest -->
 <script src="http://static.geetest.com/static/tools/gt.js"></script>
 <script>
     //发送数据
     var handlerPopup = function (captchaObj) {
     // 成功的回调
     captchaObj.onSuccess(function () {
         var validate = captchaObj.getValidate();
         var username = $("#username").val();
         var password = $("#password").val();
         $.ajax({
             url: "/login/", // 进行二次验证
             type: "post",
             dataType: "json",
             data: {
                 username: username,
                 password: password,
                 csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
                 geetest_challenge: validate.geetest_challenge,
                 geetest_validate: validate.geetest_validate,
                 geetest_seccode: validate.geetest_seccode
             },
             success: function (data) {
                 if(data.status){
                     $(".login-error").text(data.msg);
                 }else{
                     location.href = data.msg;
                 }
             }
         });
     });

     //绑定事件显示滑动验证码
     $("#login-button").click(function () {
         captchaObj.show();
     });
     // 将验证码加到id为captcha的元素里
     captchaObj.appendTo("#popup-captcha");
     // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
 };
     // 验证开始需要向网站主后台获取id,challenge,success(是否启用failback)
     $.ajax({
         url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加随机数防止缓存
         type: "get",
         dataType: "json",
         success: function (data) {
             // 使用initGeetest接口
             // 参数1:配置参数
             // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
             initGeetest({
                 gt: data.gt,
                 challenge: data.challenge,
                 product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
                 offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
                 // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
             }, handlerPopup);
         }
     });

 </script>
 </body>
 </html>

Django之验证码的更多相关文章

  1. django生成验证码

    django生成验证码 # 制作验证码 def verify_code(): # 1,定义变量,用于画面的背景色.宽.高 # random.randrange(20, 100)意思是在20到100之间 ...

  2. Django之验证码 + session 认证

    验证码 + session认证 目录结构 . └── project ├── app01 │   ├── admin.py │   ├── apps.py │   ├── __init__.py │  ...

  3. python django 实现验证码的功能

    我也是刚学Python  Django不久很多都不懂,所以我现在想一边学习一边记录下来然后大家一起讨论! 验证码功能一开始我在网上找了很多的demo但是我在模仿他们写的时候,发现在我的版本上根本就不能 ...

  4. Django 生成验证码或二维码 pillow模块

    一.安装PIL PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了.PIL功能非常强大,API也非常简单易用.   PIL模块只支持到Python 2 ...

  5. django(一)验证码

    这里讲讲在django中使用第三方插件验证码的流程. 一. 先安装pillow, 通过 python -m pip install pillow 二.安装完后,在官方网站上看操作过程.地址:pillo ...

  6. Django Redis验证码 密码 session 实例

    1.settings CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCach ...

  7. django的验证码

    pip install Pillow==3.4.1在views.py中创建一个视图函数 from PIL import Image, ImageDraw, ImageFont from django. ...

  8. Django 之验证码实现

    1. django-simple-captcha 模块 安装 django-simple-captcha pip install django-simple-captcha pip install P ...

  9. Django中验证码的登录

    需求概述 一般登录页面或者其他页面都需要验证码的功能,那在Django中如何实现呢? 这基本就需要用到第三方模块了:pillow 还需要两个文件,一个是字体文件:Monaco.ttf,另一个是一个模块 ...

随机推荐

  1. BZOJ3709 Bohater 贪心

    传送门 思路很妙-- 有个前提条件:血量无限,这样话肯定先打会回血的怪,再打会掉血的怪 对于会回血的怪,按照受到伤害的顺序从小往大打 对于会掉血的怪似乎并不是很好搞,考虑:将每一时刻的血量函数画出来, ...

  2. codeforces#1132 F. Clear the String(神奇的区间dp)

    题意:给出一个字符串S,|S|<=500.每次操作可以删除一段连续的相同字母的子串.问,最少操作多少次可以把这个字符串变成空串. 分析:刚开始的思路是,把连续的串给删除掉,然后再....贪心.完 ...

  3. iOS WebView 加载本地资源(图片,文件等)

    https://www.cnblogs.com/dhui69/p/5596917.html iOS WebView 加载本地资源(图片,文件等) NSString *path = [[NSBundle ...

  4. jvm 垃圾回收机制和算法(转)

    stop-the-world 在学习Java GC 之前,我们需要记住一个单词:stop-the-world .它会在任何一种GC算法中发生.stop-the-world 意味着JVM因为需要执行GC ...

  5. matplotlib使用

    import numpy as np import matplotlib.pyplot as plt 生成数据 mean1=[5,5] cov1=[[1,1],[1,1.5]] data=np.ran ...

  6. rsync 远程拷贝

    rsync -vzP win7.qcow2 agu@192.168.1.198:/tmp/

  7. LODOP提示、报错、现象,简短问答

    提示升级提示:“打印控件需要升级!点击这里执行升级,升级后请重新进入."“Web打印服务CLodop需升级!点击这里执行升级,升级后请刷新页面.”(新版提示) 参考http://www.c- ...

  8. Linux常用硬盘分区工具简介

    1.fdisk 查看当前硬盘分区: [root@yqtrack-zabbix /]# fdisk -l 2.cfdisk 查看当前硬盘分区: 3.sfdisk 查看当前分区: 4.parted 查看当 ...

  9. busybox(三)最小根文件系统

    目录 busybox(三)最小根文件系统 引入 构建终端 构造inittab 配置应用程序 构建C库 制作映像文件yaffs title: busybox(三)最小根文件系统 tag: arm dat ...

  10. 微服务之服务中心—zookeeper

    微服务中的服务注册与发现 传统的项目中,某个服务访问另一个服务,可以通过在配置文件中记录其他服务静态地址的形式进行访问,通常这个配置文件也很少更新,模式如下图: 而在微服务中,每个功能可能都是一个独立 ...