Flask項目--發送短信驗證碼

1.后端代碼

在這里插入圖片描述具體代碼如下:

# GET /api/v1.0/sms_codes/<mobile>?image_code=xxxx&image_code_id=xxxx
@api.route("/sms_codes/<re(r'1[34578]\d{9}'):mobile>")
def get_sms_code(mobile):"""獲取短信驗證碼"""# 獲取參數image_code = request.args.get("image_code")image_code_id = request.args.get("image_code_id")# 校驗參數if not all([image_code_id, image_code]):# 表示參數不完整return jsonify(errno=RET.PARAMERR, errmsg="參數不完整")# 業務邏輯處理# 從redis中取出真實的圖片驗證碼try:real_image_code = redis_store.get("image_code_%s" % image_code_id)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="redis數據庫異常")# 判斷圖片驗證碼是否過期if real_image_code is None:# 表示圖片驗證碼沒有或者過期return jsonify(errno=RET.NODATA, errmsg="圖片驗證碼失效")# 刪除redis中的圖片驗證碼,防止用戶使用同一個圖片驗證碼驗證多次try:redis_store.delete("image_code_%s" % image_code_id)except Exception as e:current_app.logger.error(e)# 與用戶填寫的值進行對比if real_image_code.lower() != image_code.lower():# 表示用戶填寫錯誤return jsonify(errno=RET.DATAERR, errmsg="圖片驗證碼錯誤")# 判斷對于這個手機號的操作,在60秒內有沒有之前的記錄,如果有,則認為用戶操作頻繁,不接受處理try:send_flag = redis_store.get("send_sms_code_%s" % mobile)except Exception as e:current_app.logger.error(e)else:if send_flag is not None:# 表示在60秒內之前有過發送的記錄return jsonify(errno=RET.REQERR, errmsg="請求過于頻繁,請60秒后重試")# 判斷手機號是否存在try:user = User.query.filter_by(mobile=mobile).first()except Exception as e:current_app.logger.error(e)else:if user is not None:# 表示手機號已存在return jsonify(errno=RET.DATAEXIST, errmsg="手機號已存在")# 如果手機號不存在,則生成短信驗證碼sms_code = "%06d" % random.randint(0, 999999)# 保存真實的短信驗證碼try:redis_store.setex("sms_code_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)# 保存發送給這個手機號的記錄,防止用戶在60s內再次出發發送短信的操作redis_store.setex("send_sms_code_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="保存短信驗證碼異常")# 發送短信# 使用celery異步發送短信, delay函數調用后立即返回(非阻塞)# send_sms.delay(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES/60)], 1)# 返回異步任務的對象result_obj = send_sms.delay(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES/60)], 1)print(result_obj.id)# 通過異步任務對象的get方法獲取異步任務的結果, 默認get方法是阻塞的ret = result_obj.get()print("ret=%s" % ret)# 返回值# 發送成功return jsonify(errno=RET.OK, errmsg="發送成功")

2.前端html代碼

在這里插入圖片描述具體代碼如下:

<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>愛家-注冊</title><link href="/static/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet"><link href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"><link href="/static/css/reset.css" rel="stylesheet"><link href="/static/css/ihome/main.css" rel="stylesheet"><link href="/static/css/ihome/register.css" rel="stylesheet">
</head>
<body><div class="container"><div class="logo-bar"><a href="/"><img src="/static/images/logo@128x59.png"></a></div><form class="form-register"><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-mobile fa-2x fa-fw"></i></div><input type="number" class="form-control" name="mobile" id="mobile" placeholder="手機號" required></div></div><div class="error-msg" id="mobile-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-image fa-lg fa-fw"></i></div><input type="text" class="form-control" name="imagecode" id="imagecode" placeholder="圖片驗證碼" required><div class="input-group-addon image-code" onclick="generateImageCode();"><img src=""></div></div></div><div class="error-msg" id="image-code-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-envelope-o fa-lg fa-fw"></i></div><input type="text" class="form-control" name="phonecode" id="phonecode" placeholder="短信驗證碼" required><div class="phonecode input-group-addon"><a class="phonecode-a" href="javascript:;" onclick="sendSMSCode();">獲取驗證碼</a></div></div></div><div class="error-msg" id="phone-code-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-lock fa-lg fa-fw"></i></div><input type="password" class="form-control" name="password" id="password" placeholder="密碼" required></div></div><div class="error-msg" id="password-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-lock fa-lg fa-fw"></i></div><input type="password" class="form-control" name="password2" id="password2" placeholder="確認密碼" required></div></div><div class="error-msg" id="password2-err"><i class="fa fa-exclamation-circle"></i><span></span></div><button type="submit" class="btn btn-lg btn-theme btn-block">立即注冊</button><p class="login-a">已有賬號,<a href="/login.html">立即登陸</a></p></form></div><script src="/static/js/jquery.min.js"></script><script src="/static/plugins/bootstrap/js/bootstrap.min.js"></script><script src="/static/js/ihome/register.js"></script>
</body>
</html>

3.前端js代碼

在這里插入圖片描述具體代碼如下:

function sendSMSCode() {// 點擊發送短信驗證碼后被執行的函數$(".phonecode-a").removeAttr("onclick");var mobile = $("#mobile").val();if (!mobile) {$("#mobile-err span").html("請填寫正確的手機號!");$("#mobile-err").show();$(".phonecode-a").attr("onclick", "sendSMSCode();");return;} var imageCode = $("#imagecode").val();if (!imageCode) {$("#image-code-err span").html("請填寫驗證碼!");$("#image-code-err").show();$(".phonecode-a").attr("onclick", "sendSMSCode();");return;}// 構造向后端請求的參數var req_data = {image_code: imageCode, // 圖片驗證碼的值image_code_id: imageCodeId // 圖片驗證碼的編號,(全局變量)};// 向后端發送請求$.get("/api/v1.0/sms_codes/"+ mobile, req_data, function (resp) {// resp是后端返回的響應值,因為后端返回的是json字符串,// 所以ajax幫助我們把這個json字符串轉換為js對象,resp就是轉換后對象if (resp.errno == "0") {var num = 60;// 表示發送成功var timer = setInterval(function () {if (num >= 1) {// 修改倒計時文本$(".phonecode-a").html(num + "秒");num -= 1;} else {$(".phonecode-a").html("獲取驗證碼");$(".phonecode-a").attr("onclick", "sendSMSCode();");clearInterval(timer);}}, 1000, 60)} else {alert(resp.errmsg);$(".phonecode-a").attr("onclick", "sendSMSCode();");}});
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/452682.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/452682.shtml
英文地址,請注明出處:http://en.pswp.cn/news/452682.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Jenkins系列之五——通過Publish over SSH插件實現遠程部署

Jenkins通過Publish over SSH插件實現遠程部署 步湊一、配置ssh免秘鑰登錄 部署詳情地址&#xff1a;http://www.cnblogs.com/Dev0ps/p/8259099.html 步湊二、安裝Publish over SSH插件 插…

Java高級應用開發之Servlet

學習路徑&#xff1a; 1.Servlet簡介 2.Servlet基礎 3.表單處理 4.請求頭信息 5.響應頭信息 6.cookie 7.session 8.scope: Servlet Context 全局變量 Http Session 會話變量 Http Servlet Request 請求變量 9.Filter Filter是一種特殊的Servlet&#xff0c;其核心函數doFilter(…

typedef 數組使用詳解

typedef到處都是&#xff0c;但是能夠真正懂得typedef使用的不算太多。對于初學者而言&#xff0c;看別人的源碼時對到處充斥的typedef往往不知所錯&#xff0c;而參考書又很少&#xff0c;所以在此給出一個源碼&#xff0c;供大家參考。 懂得這些&#xff0c;基本上是 對typed…

php柱狀圖實現年齡分布,考官雅思寫作小作文滿分范文 柱狀圖:年齡分布

考官雅思寫作小作文滿分范文 柱狀圖:年齡分布2017年06月12日14:48 來源&#xff1a;小站教育作者&#xff1a;小站雅思編輯參與(40)閱讀(63981)摘要&#xff1a;為大家分享前考官simon演示的9分雅思小作文。考官親筆&#xff0c;用最正統的4段式寫作&#xff0c;本文主題-柱狀圖…

Flask項目--注冊

0.效果展示 1.后端代碼 # coding:utf-8from . import api from flask import request, jsonify, current_app, session from ihome.utils.response_code import RET from ihome import redis_store, db, constants from ihome.models import User from sqlalchemy.exc import I…

圖片處理

//圖片處理public function img(){//讀取圖片$imageImage::open(./img/02.jpg);//dump($image);//獲取圖片的信息// 返回圖片的寬度$width $image->width();// 返回圖片的高度$height $image->height();// 返回圖片的類型$type $image->type();// 返回圖片的mime類…

react 項目總結

前言 最近在寫一個項目,在寫react的過程中遇到過很多坑,現在總結一下,為以后的項目作參考.另外借此項目來比較一下 vue.js 和 react.js 之間的一些異同. 先說說組件 剛剛開始寫組件的時候&#xff0c;感覺難度不大&#xff08;跟vue差不多&#xff09;。最有意思的應該是jsx語法…

現代數字影視 電影使用標準

1、國際數字電影標準1&#xff09;DCI&#xff08;Digital Cinema Initiatives數字影院系統規范&#xff09;美國好萊塢七大制片公司——Disney、MGM、Fox、Paramount Pictures、Sony Pictures Entertainment、Universal Studios和Warner Bros于2002年聯合成立了DCI機構&#x…

數據流圖 系統流程圖 程序流程圖 系統結構圖聯系與區別

1.數據流圖&#xff08;Data Flow Diagram&#xff09;&#xff0c;簡稱DFD&#xff0c;它從數據傳遞和加工角度&#xff0c;以圖形方式來表達系統的邏輯功能、數據在系統內部的邏輯流向和邏輯變換過程&#xff0c;是結構化系統分析方法的主要表達工具及用于表示軟件模型的一種…

Linux--安裝yum源

linux配置yum源 一、修改yum的配置文件 /etc/yum.repos.d/xxx.repo 1、進入yum配置文件目錄 # cd /etc/yum.repos.d 2、刪除全部原有的文件 # rm -rf * 3、新建一個yum的配置文件 # vi my.repo [myrepo] 標識配置文件名稱&#xff08;名字隨意&#xff09; namemyrepo 標識yum …

在 Confluence 6 中禁用 workbox 應用通知

如果你選擇 不提供應用通知&#xff08;does not provide in-app notifications&#xff09;&#xff1a; Confluence workbox 圖標將不會可見同時用戶也不能在這個服務器上訪問 workbox。這個 Confluence 服務器將不會發送消息到 workbox 中&#xff0c;同時也不會發送消息到其…

迄今為止最快的 JSON 序列化工具 Jil

2019獨角獸企業重金招聘Python工程師標準>>> 迄今為止最快的 JSON 序列化工具 Jil https://github.com/kevin-montrose/Jil 轉載于:https://my.oschina.net/xainghu/blog/1621365

mysql數據庫訪問編程,mysql 連接數據庫

1、首先啟動mysql 并鏈接數據 小意思吧&#xff01;都會了是吧mysql -uroot -p //連接數據net start mysql // 啟動mysql2、查詢當前 服務器里有哪些數據show databases;3、創建數據庫create database jddb -------數據庫名字(jddb)4、 使用數據庫use jddb;5、查詢當前數據庫下…

linux多線程 pthread用法

#include int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr, void *(*start_rtn)(void),void *restrict arg); Returns: 0 if OK, error number on failure 第一個參數為指向線程標識符的指針。 第二個參數用來設置線程屬性。 第三個參數是…

什么是數據字典

數據字典是指對數據的數據項、數據結構、數據流、數據存儲、處理邏輯、外部實體等進行定義和描述&#xff0c;其目的是對數據流程圖中的各個元素做出詳細的說明。 數據字典最重要的作用是作為分析階段的工具。任何字典最重要的用途都是供人查詢對不了解的條目的解釋&#xff0c…

Flsak愛家租房--個人信息

0.頁面展示效果 1.設置用戶頭像–后端代碼 # coding:utf-8from . import api from ihome.utils.commons import login_required from flask import g, current_app, jsonify, request, session from ihome.utils.response_code import RET from ihome.utils.image_storage impo…

json返回值為null顯示key值的設置

使用的是阿里的json ----------com.alibaba.fastjson.JSONObject; Map<String,Object> map new HashMap<String,Object>(); return JSONObject.toJSONString(map); --------轉義的時候&#xff0c;map中值是null的字段會被忽略掉&#xff0c;轉義的json沒有帶n…

C++ string::size_type

從邏輯上講&#xff0c;size()成員函數應該似乎返回整型數值&#xff0c;但事實上&#xff0c;size操作返回是string::size_type類型的值。string類類型和其他許多庫類型都定義了一些配套類型(companion type)。通過這些配套類型&#xff0c;庫函數的使用就與機器無關(machine-…

需求分遵循的準則

?必須理解并描述問題的信息域&#xff0c;根據這條準則應該建立數據模型。 ?必須定義軟件應完成的功能&#xff0c;這條準則要求建立功能模型。 ?必須描述作為外部事件結果的軟件行為&#xff0c;這條準則要求建立行為模型 ?必須對描述信息、功能和行為的模型進行分解&…

MATLAB顯示錯誤使用untitled,新手,用gui界面畫李薩如圖,出錯,求解答

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓function varargout untitled1(varargin)% UNTITLED1 MATLAB code for untitled1.fig% UNTITLED1, by itself, creates a new UNTITLED1 or raises the existing% singleton*.%% H UNTITLED1 returns the handle to a new UNTITL…