圖形 / 短信 :驗證碼

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();
View Code

 

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)
View Code

 

 

圖形驗證碼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

相關文章
相關標籤/搜索