message.js文件:

  1 // 错误消息提示框
  2
  3 function Message() {
  4     var self = this;
  5     self.isAppended = false;
  6     self.wrapperHeight = 48;
  7     self.wrapperWidth = 300;
  8     self.initStyle();
  9     self.initElement();     // 初始化元素;
 10     self.listenCloseEvent();
 11 }
 12
 13 // 定义各类提示框的显示颜色;
 14 Message.prototype.initStyle = function () {
 15     var self = this;
 16     self.errorStyle = {
 17         'wrapper':{
 18             'background': '#f2dede',
 19             'color': '#993d3d'
 20         },
 21         'close':{
 22             'color': '#993d3d'
 23         }
 24     };
 25     self.successStyle = {
 26         'wrapper':{
 27             'background': '#dff0d8',
 28             'color': '#468847'
 29         },
 30         'close': {
 31             'color': "#468847"
 32         }
 33     };
 34     self.infoStyle = {
 35         'wrapper': {
 36             'background': '#d9edf7',
 37             'color': '#5bc0de'
 38         },
 39         'close': {
 40             'color': '#5bc0de'
 41         }
 42     }
 43 };
 44
 45 // 提示框的样式;
 46 Message.prototype.initElement = function () {
 47     var self = this;
 48     // 创建div用来存储错误消息;
 49     self.wrapper = $("<div></div>");
 50     self.wrapper.css({
 51         'padding': '10px',
 52         'font-size': '14px',
 53         'width': '300px',
 54         'position': 'fixed',
 55         'z-index': '10000',
 56         'left': '50%',
 57         'top': '-48px',
 58         'margin-left':'-150px',
 59         'height': '48px',
 60         'box-sizing': 'border-box',
 61         'border': '1px solid #ddd',
 62         'border-radius': '4px',
 63         'line-height': '24px',
 64         'font-weight': 700
 65     });
 66     // 关闭按钮;
 67     self.closeBtn = $("<span>×</span>");
 68     self.closeBtn.css({
 69         'font-family': 'core_sans_n45_regular,"Avenir Next","Helvetica Neue",Helvetica,Arial,"PingFang SC","Source Han Sans SC","Hiragino Sans GB","Microsoft YaHei","WenQuanYi MicroHei",sans-serif;',
 70         'font-weight': '700',
 71         'float': 'right',
 72         'cursor': 'pointer',
 73         'font-size': '22px'
 74     });
 75     // 用来存储错误消息的文本;
 76     self.messageSpan = $("<span class='xfz-message-group'></span>");
 77
 78     self.wrapper.append(self.messageSpan);
 79     self.wrapper.append(self.closeBtn);
 80 };
 81
 82 // 关闭时错误框上移,即隐藏到页面后面;
 83 Message.prototype.listenCloseEvent = function () {
 84     var self = this;
 85     self.closeBtn.click(function () {
 86         self.wrapper.animate({"top":-self.wrapperHeight});
 87     });
 88 };
 89
 90 Message.prototype.showError = function (message) {
 91     this.show(message,'error');
 92 };
 93
 94 Message.prototype.showSuccess = function (message) {
 95     this.show(message,'success');
 96 };
 97
 98 Message.prototype.showInfo = function (message) {
 99     this.show(message,'info');
100 };
101
102 // 添加错误信息并将错误框像下移动,显示在页面中;
103 Message.prototype.show = function (message,type) {
104     var self = this;
105     if(!self.isAppended){
106         $(document.body).append(self.wrapper);
107         self.isAppended = true;
108     }
109     self.messageSpan.text(message);
110     if(type === 'error') {
111         self.wrapper.css(self.errorStyle['wrapper']);
112         self.closeBtn.css(self.errorStyle['close']);
113     }else if(type === 'info'){
114         self.wrapper.css(self.infoStyle['wrapper']);
115         self.closeBtn.css(self.infoStyle['close']);
116     }else{
117         self.wrapper.css(self.successStyle['wrapper']);
118         self.closeBtn.css(self.successStyle['close']);
119     }
120     self.wrapper.animate({"top":0},function () {
121         setTimeout(function () {
122             self.wrapper.animate({"top":-self.wrapperHeight});
123         },3000);
124     });
125 };
126
127 // 将Message对象绑定到window窗口,一个全局对象;
128 window.messageBox = new Message();

View Code

restful.py文件:

 1 from django.http import JsonResponse
 2
 3 class HttpCode(object):
 4     ok = 200            # 正常运行;
 5     paramserror = 400   # 参数错误;
 6     unauth = 401        # 没授权;
 7     methoderror = 405   # 请求方法错误;
 8     servererror = 500   # 服务器内部错误;
 9
10 def result(code=HttpCode.ok,message='',data=None,kwargs=None):
11     json_dict = {'code':code,'message':message,'data':data}
12     if kwargs and isinstance(kwargs,dict) and kwargs.keys():
13         json_dict.update(kwargs)
14     return JsonResponse(json_dict)
15
16 def ok():
17     return result()
18
19 def params_error(message='',data=None):
20     return result(code=HttpCode.paramserror,message=message,data=data)
21
22 def unauth(message='',data=None):
23     return result(code=HttpCode.unauth,message=message,data=data)
24
25 def method_error(message='',data=None):
26     return result(code=HttpCode.methoderror,message=message,data=data)
27
28 def server_error(message='',data=''):
29     return result(code=HttpCode.servererror,message=message,data=data)

View Code

图形验证码

 1 from django.http import HttpResponse
 2 from utils.captcha.xfzcaptcha import Captcha
 3 # 内存管道,存储Bytes类型的数据
 4 from io import BytesIO
 5
 6 # 图形验证码;
 7 def img_captcha(request):
 8     text,image = Captcha.gene_code()
 9     # BytesIO:相当于一个管道,用来存储图片的数据流;
10     out = BytesIO()
11     # 调用image的save方法,将image对象保存到BytesIO中;
12     image.save(out,'png')
13     # 将BytesIO的文件指针移到到最开始的位置;
14     out.seek(0)
15     response = HttpResponse(content_type='image/png')
16     # 从BytesIO管道中,读取出图片数据,保存到response对象上;
17     response.write(out.read())
18     response['Content-length'] = out.tell()
19     return  response

1 # 图形验证码的HTML文件
2 <img src="{% url 'xfzauth:img_captcha' %}" alt="" class="img-captcha">

 1 # App的url;
 2 from django.urls import path
 3 from . import views
 4
 5 app_name = "xfzauth"
 6
 7 urlpatterns = [
 8     path('img_captcha/',views.img_captcha,name='img_captcha')
 9 ]
10
11 # 项目url;
12 from django.urls import path,include
13
14 urlpatterns = [
15     path('course/',include('apps.course.urls')),
16 ]

 1 // js文件,图形验证码的点击刷新事件;
 2
 3 function Auth(){
 4
 5 };
 6 Auth.prototype.listenImageCaptchaEvent  = function(){
 7     var imgCaptcha = $(".img-captcha");
 8     imgCaptcha.click(function () {
 9         imgCaptcha.attr("src","/account/img_captcha/"+"?random="+Math.random())
10     });
11 };
12
13 Auth.prototype.run(){
14     var self = this;
15     self.listenImageCaptchaEvent();
16 };
17
18 $(function () {
19     var auth = new Auth();
20     auth.run();
21 });

短信验证码:

一、使用阿里云短信服务平台进行短信服务;

1、登录阿里云:https://homenew.console.aliyun.com/;

2、登录在个人头像下拉框点击 accesskeys ,使用子用户;

3、添加用户:记住用户的 AccessKey ID 和 AccessKeySecret (复制保存下来,后续用到),并添加短信的权限;

4、搜索进入 短信服务,点击国内消息,依次添加签名与模板,需要2小时的时间审核通过;成功后可在快速学习进行测试。

二 、在python中使用

1、在阿里云的短信服务页面下方:帮助文档 --> 开发指南 --> API文档 --> python --> 短信发送API(SendSms);

下载python的SDK:https://help.aliyun.com/document_detail/55359.html?spm=a2c4g.11186623.2.18.19936540mAyniL

2、cmd进入python虚拟环境中,cd到SDK存放的位置进行安装:python setup.py install;

3、在个人新建的工具包 utils 下新建 aliyunsdk python包,将“”sysms_python中的“aliyunsdkdysmsapi”包复制过去;并在同目录下新建 aliyunsms.py 文件;

aliyunsms.py文件:

 1 # -*- coding: utf-8 -*-
 2 import sys
 3 from aliyunsdkdysmsapi.request.v20170525 import SendSmsRequest
 4 from aliyunsdkdysmsapi.request.v20170525 import QuerySendDetailsRequest
 5 from aliyunsdkcore.client import AcsClient
 6 import uuid
 7 from aliyunsdkcore.profile import region_provider
 8 from aliyunsdkcore.http import method_type as MT
 9 from aliyunsdkcore.http import format_type as FT
10 import json
11
12
13 """
14 短信业务调用接口示例,版本号:v20170525
15
16 """
17 # 写上自己创建用户时的ID;
18 ACCESS_KEY_ID = "LTAIYWdLG8V74hLy"
19 ACCESS_KEY_SECRET = "jdDFgzqY4jP0smr7qsntySkPZZvr04"
20
21 # 内容不更改;
22 REGION = "cn-hangzhou"
23 PRODUCT_NAME = "Dysmsapi"
24 DOMAIN = "dysmsapi.aliyuncs.com"
25
26 acs_client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION)
27 region_provider.add_endpoint(PRODUCT_NAME, REGION, DOMAIN)
28
29
30 def send_sms(phone_numbers,code):
31     business_id = uuid.uuid1()
32     sign_name = '小饭桌应用'    # 签名;
33     template_code = 'SMS_165692133'    # 模板ID;
34     template_param = json.dumps({"code":code})
35     smsRequest = SendSmsRequest.SendSmsRequest()
36     # 申请的短信模板编码,必填;
37     smsRequest.set_TemplateCode(template_code)
38     # 短信模板变量参数;
39     if template_param is not None:
40         smsRequest.set_TemplateParam(template_param)
41     # 设置业务请求流水号,必填;
42     smsRequest.set_OutId(business_id)
43     # 短信签名;
44     smsRequest.set_SignName(sign_name)
45     # 短信发送的号码列表,必填;
46     smsRequest.set_PhoneNumbers(phone_numbers)
47     # 调用短信发送接口,返回json;
48     smsResponse = acs_client.do_action_with_exception(smsRequest)
49     return smsResponse

views.py文件:

 1 from utils import restful
 2 from utils.captcha.xfzcaptcha import Captcha
 3 from django.http import HttpResponse
 4 from utils.aliyunsdk import aliyunsms
 5
 6 # 接收的号码与验证码内容;
 7 def sms_captcha(request):
 8     # /sms_captcha/?telephone=xxx
 9     telephone = request.GET.get('telephone')
10     code = Captcha.gene_text()
11     result = aliyunsms.send_sms(telephone,code)
12     print(result)
13     return restful.ok()

 1 // 短信验证码 js 文件;
 2 function Auth() {
 3     var self = this;
 4     self.smsCaptcha = $('.SMS-captcha-btn');
 5 }
 6
 7 Auth.prototype.smsSuccessEvent = function(){
 8     var self = this;
 9     messageBox.showSuccess('短信验证码发送成功!');
10     self.smsCaptcha.addClass('disabled');   // 添加另一个表示无法点击的类的样式;
11     var count = 60;
12     self.smsCaptcha.unbind('click');    // 解除点击事件;
13     var timer = setInterval(function () {
14         self.smsCaptcha.text(count+'s');
15         count -= 1;
16         if(count<=0){
17             clearInterval(timer);
18             self.smsCaptcha.removeClass('disabled');
19             self.smsCaptcha.text('发送验证码');
20             self.listenSmsCaptchaEvent();
21         }
22     },1000);
23 };
24
25 // 监听短信验证码;
26 Auth.prototype.listenSmsCaptchaEvent = function(){
27     var self = this;
28     var telephoneInput = $(".signup-group input[name='telephone']");
29     self.smsCaptcha.click(function () {
30         var telephone = telephoneInput.val();
31         if(!telephone){
32             messageBox.showInfo('请输入手机号码!');
33         }
34         xfzajax.get({
35             'url': '/account/sms_captcha/',
36             'data':{
37                 'telephone': telephone,
38             },
39             'success': function (result) {
40                 if(result['code'] == 200){
41                     self.smsSuccessEvent();
42                 }
43             },
44             'fail': function (error) {
45                 console.log(error)
46             }
47         });
48     });
49 };
50 // 运行;
51 Auth.prototype.run = function () {
52     self.listenSmsCaptchaEvent();
53 };
54
55 $(function () {
56     var auth = new Auth();
57     auth.run();
58 });
59
60 $(function () {
61     var frontBase = new FrontBase();
62     frontBase.run();
63 });

可能出现的问题:

  在初步安装SDK时, aliyunsdkcore 工具包没有一起被安装,导致无法调用,需手动重新安装:pip install aliyun-python-sdk-core(https://develop.aliyun.com/tools/sdk?#/python)

转载于:https://www.cnblogs.com/liqiongming/p/10898872.html

图形 / 短信 :验证码相关推荐

  1. 登录之图形跟短信验证码

    1.html代码 <ul class="login-from"><li class="flexbox flexbox-middle" > ...

  2. 短信验证码、图形验证码、邮件验证的自动化测试

    短信验证码.图形验证码.邮件验证问题在自动化测试中是一个很常见的问题,也是一个很棘手的问题.设计的初衷其实就是为了防自动化,防止一些人利用自动工具恶意攻击网站,而很不幸的是,我们所使用的一些自动化测试 ...

  3. java+vue3实现生成、验证图形验证码,和手机短信验证码

    一.效果图 二.实现生成图形验证码.校验验证码 1.实现后端接口 ①控制层代码 /*** 生成图片验证码* time用于保证每次可以刷新图片验证码*/@GetMapping("authCod ...

  4. 图形验证码和短信验证码

    图形验证码 注意事项 在虚拟环境中安装Pillow 字体文件需要在环境中测试一下(字体文件习惯放在和验证码同层目录下) import random # Image:是一个画板(context),Ima ...

  5. Flask项目实战——6—(前台用户模型、前台登录注册、图形验证码、手机短信验证码、添加表单验证短信验证码请求)

    1.前台用户模型 前台用户模型定义 创建前台模型文件 apps/front/models.py # -*- encoding: utf-8 -*- """ @File : ...

  6. locvps的自动注册(图形和短信验证码的自动识别获取)

    1.通过selenuim实现自动注册 2.图形验证码的识别(简单识别,效果差,可以多循环几次,或者通过二值化处理提高准确率) 3.短信验证码的获取(使用接码平台调用API) selenuim操作 dr ...

  7. 【5分钟教你】3种实现验证码功能-数字短信验证码-图形验证码-滑动验证码

    摘要:我们在做一些后台系统的登录验证的时候.难免会用到验证码功能,来辅助进行验证,提高安全性,在我们日常生活中,验证方式无处不在,最多的是短信验证码的方式,通过点击发送验证码,然后手机接收短信,填写验 ...

  8. 图形验证码+短信验证码【Java应用实例】

    一.图形验证码的实现 1.1 简介 常在网上晃悠的人,对下面这张图都不会陌生.特别是在注册新账号.确认交易时,它们都会频繁出现,要求我们输入正确的验证码,那这些看上去跟我们要做的事情完全无关的验证码到 ...

  9. selenium之自动登录获取短信验证码或者图形验证码的方法

    对于很多项目的登录界面都是需要一个验证码的,对于验证码的方式有两种,一种是纯数字,就是验证码是通过发送短信的这种,这种比较好获取,另一种是图形验证码,有些图形验证码比较简单,比如纯数字的,有些比较复杂 ...

最新文章

  1. Java @override报错的解决方法 .
  2. HazelCast的Spring-Boot和Cache抽象
  3. MSSQL 2005数据库与SP4补丁安装
  4. centos7安装telnet后/etc/xinetd.d/telnet下没有telnet
  5. oracle-11g-R2监听文件配置
  6. debian 删除mysql数据库_Debian中完全卸载MySQL的方法
  7. CentOS 5.4 制作 Python 2.6 RPM 包的方法
  8. python中kmeans怎么导入数据集_通过Python实践K-means算法
  9. ajax原生为什么else会执行2次,为什么这里的alert会执行2次?
  10. Invalid maximum heap size: -Xmx
  11. 车辆颜色识别opencv
  12. Data Driven Modeling 课程
  13. 【Android取证篇】华为手机OTG备份密码重置教程
  14. iphone7刷入linux,iPhone7怎么进入DFU模式 iPhone7刷机步骤【详解】
  15. Linux下用火焰图进行性能分析
  16. 【工具安装】Quartus II 安装与驱动
  17. 网易2018校园招聘编程题真题集合 详解
  18. ZUCC_计算机网络实验_实验03 交换机基本配置
  19. 极品飞车服务器维修好久,极品飞车无限狂飙被封锁多久能解 | 手游网游页游攻略大全...
  20. reduce()方法详解

热门文章

  1. 手术及切口分类与伤口愈合分级以及ASA麻醉分级
  2. java小型超市系统_Java小型超市收银系统
  3. Jmeter书中不会教你的(94)——将时间戳转换为日期格式
  4. ubuntu13.10编译android文件系统4.0.4错误全部解析
  5. windows从零搭建hugo博客
  6. 搞笑台词,意想不到之语却似在情理之中
  7. MySQL同步机制、主从复制半同步和双主配置
  8. 开源的毕业设计—3D虚拟社区
  9. centos7已有数据硬盘挂载_centos7硬盘分区、挂载和数据迁移
  10. 嵌入式相关开源项目、库、资料------持续更新中