flask项目之5:短信验证码发送
生活随笔
收集整理的這篇文章主要介紹了
flask项目之5:短信验证码发送
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概述:
- 短信驗證碼的發送需要限制驗證碼的發送間隔不能不停的發,因為測試時發送的驗證碼是要花錢的,不可能不花錢就辦事
- 短信驗證碼要根據圖片驗證碼是不是正確再進行發,
進行短信驗證碼的實驗要測試容聯云平臺;然后將短信驗證碼的類設置為單例模式(每次實例化都是用的一個地址,不會產生新的類) - 1.容聯云平臺:
- 2.單例模式
- 3.驗證碼相關邏輯與實現位置
容聯云平臺測試:
http://yuntongxun.com/member/main
點擊開發文檔,可以查看相關的開發文檔,
在這里主要用到的就是短信開發手冊
http://doc.yuntongxun.com/space/5a5098313b8496dd00dcdd7f
以下為容聯云平臺的python SDK
https://doc.yuntongxun.com/p/5f029ae7a80948a1006e776e
調用示例:
使用前先要安裝ronglian_sms_sdk
- 單例模式:
通過這樣的方式獲得的實例共用一個空間
如果采用傳統方式,則每個實例占一個空間,實例不再列舉
短信驗證碼發送:
在libs中新建包:ronglianyun,新建ccp_sms.py文件,在其中新建發送模板的單例類
然后在藍圖verify_code.py新建路由:
@api.route("/sms_codes/<re(r'1[345678]\d{9}'):mobile>") def get_sms_code(mobile):"""獲取短信驗證碼"""# 獲取參數# 圖片驗證碼image_code = request.args.get('image_code')# UUIDimage_code_id = request.args.get('image_code_id')# 校驗參數if not all([image_code, image_code_id]):return jsonify(errno=RET.PARAMERR, errmsg='參數不完整')# 業務邏輯# 從redis中取出驗證碼try:real_image_code = redis_store.get('image_code_%s' % image_code_id)except Exception as e:logging.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:logging.error(e)# print(real_image_code) b'RVMJ'# 與用戶填寫的圖片驗證碼對比real_image_code = real_image_code.decode()if real_image_code.lower() != image_code.lower():return jsonify(errno=RET.DATAERR, errmsg='圖片驗證碼錯誤')# 判斷手機號的操作try:send_flag = redis_store.get('send_sms_code_%s' % mobile)except Exception as e:logging.error(e)else:if send_flag is not None:return jsonify(errno=RET.REQERR, errmsg='請求過于頻繁')# 判斷手機號是否存在try:user = User.query.filter_by(mobile=mobile).first()except Exception as e:logging.error(e)else:if user is not None:# 表示手機號已經被注冊過return jsonify(errno=RET.DATAEXIST, errmsg='手機號已經存在')# 生成短信驗證碼sms_code = "%06d" % random.randint(0, 999999)# 保存真實的短信驗證碼到redistry:# redis管道pl = redis_store.pipeline()pl.setex("sms_code_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)# 保存發送給這個手機號的記錄pl.setex('send_sms_code_%s' % mobile, constants.SNED_SMS_CODE_EXPIRES, 1)pl.execute()except Exception as e:logging.error(e)return jsonify(errno=RET.DBERR, errmsg='保存短信驗證碼異常')# 發短信try:ccp = CCP()result = ccp.send_message(mobile, (sms_code, int(constants.SMS_CODE_REDIS_EXPIRES/60)), 1)except Exception as e:logging.error(e)return jsonify(errno=RET.THIRDERR, errmsg='發送異常')# 返回值if result == 0:return jsonify(errno=RET.OK, errmsg='發送成功')else:return jsonify(errno=RET.THIRDERR, errmsg='發送失敗')總結
以上是生活随笔為你收集整理的flask项目之5:短信验证码发送的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows cmd关机重启命令
- 下一篇: 浙江大学郑强教授的演讲(国民必看)