message.js文件:css
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();
restful.py文件:html
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)
图形验证码:python
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 });
短信验证码:ajax
1、使用阿里云短信服务平台进行短信服务;django
一、登陆阿里云:https://homenew.console.aliyun.com/;json
二、登陆在我的头像下拉框点击 accesskeys ,使用子用户;
api
三、添加用户:记住用户的 AccessKey ID 和 AccessKeySecret (复制保存下来,后续用到),并添加短信的权限;服务器
四、搜索进入 短信服务,点击国内消息,依次添加签名与模板,须要2小时的时间审核经过;成功后可在快速学习进行测试。
restful
二 、在python中使用app
一、在阿里云的短信服务页面下方:帮助文档 --> 开发指南 --> API文档 --> python --> 短信发送API(SendSms);
下载python的SDK:https://help.aliyun.com/document_detail/55359.html?spm=a2c4g.11186623.2.18.19936540mAyniL
二、cmd进入python虚拟环境中,cd到SDK存放的位置进行安装:python setup.py install;
三、在我的新建的工具包 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)