当前位置:网站首页>Flask发送验证码逻辑
Flask发送验证码逻辑
2022-07-26 00:12:00 【du fei】
发送短信验证码
- 安装第三方库
pip install ronglian_sms_sdk
- 还要设置一个配置文件settings/config.py写入代码
from settings.secret import SecretConfig
class DefaultConfig(SecretConfig):
""" 默认配置项 """
SECRET_KEY = 'haoiehteasdsd'
SQLALCHEMY_DATABASE_URI = ''
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
class DevConfig(DefaultConfig):
""" 开发阶段配置项 """
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/news'
- 创建一个utils/SmsTools.py文件写入代码
from ronglian_sms_sdk import SmsSDK
from flask import current_app
import json, redis
class SmsTool():
""" 发送短信类 """
def __init__(self):
accId = current_app.config.get('RL_ACC_ID') # 主账户ID
accToken = current_app.config.get('RL_ACC_TOKEN') # 账户授权令牌
appId = current_app.config.get('RL_APP_ID') # 默认
# 实例化SmsSDK
self.sdk = SmsSDK(accId, accToken, appId)
host = current_app.config.get('REDIS_HOST')
port = current_app.config.get('REDIS_PORT')
self.red = redis.Redis(host=host, port=port)
def send(self, phone, code):
""" :param phone: :param code: :return: """
tid = current_app.config.get('RL_TID')
# 有效期
t = current_app.config.get('SMS_TIME')
datas = (code, t)
# 存储redis
self.red.set(phone, code, ex=t * 60)
# 发送短信验证码
rs = self.sdk.sendMessage(tid, phone, datas) # 返回的是JSON字符串
rs_data = json.loads(rs)
if rs_data['statusCode'] == '000000':
return True
return False
# if __name__ == '__main__':
# # 开启上下文换进
# from app import app
#
# with app.app_context():
# s = SmsTool()
# rs = s.send('17559511990', '6666')
# print(rs)
- 直接调用即可
class SmsCodeView(Resource):
def get(self):
req = reqparse.RequestParser()
req.add_argument('mobile')
args = req.parse_args()
sms_code = random.randint(10, 99)
s = SmsTool()
ser = s.send(args['mobile'], sms_code)
if not ser:
return jsonify({
'code': 400, 'msg': '发送失败'})
return jsonify({
'code': 200, 'msg': '已发送请注意查收'})
api.add_resource(SmsCodeView, '/sms')
token的生成
- 封装一个生成token的方法
import time
import jwt
from flask import current_app
class JwtTool():
def create(self, payload, ex=3600):
""" 生成jwt :param payload: :return: """
payload['exp'] = int(time.time()) + ex
print(payload)
secret_key = current_app.config.get('SECRET_KEY')
token = jwt.encode(payload, key=secret_key, algorithm='HS256')
print(token)
return token
def valid(self, token):
secret_key = current_app.config.get('SECRET_KEY')
try:
time.sleep(2)
payload = jwt.decode(token, secret_key, algorithms='HS256')
print(payload)
return payload
except Exception as e:
print(e)
return False
if __name__ == '__main__':
from app import app
with app.app_context():
j = JwtTool()
token_jwt = j.create({
'aaa': 'bbb'})
j.valid(token_jwt)
边栏推荐
- MySQL——多版本并发控制(MVCC)
- [hero planet July training leetcode problem solving daily] 25th tree array
- Markdown writing platform
- "Animal coin" is fierce, trap or opportunity? 2021-05-12
- J9 number theory: what is Dao mode? Obstacles to the development of Dao
- Js理解之路:Object.call与Object.create()实现继承的原理
- FreeMarker view integration
- Pytoch learning record (I): introduction to pytoch
- This time, thoroughly understand promise principle
- LeetCode_ 55_ Jumping game
猜你喜欢

Leetcode high frequency question 66. add one, give you an array to represent numbers, then add one to return the result

URL address mapping configuration

网站服务器停止响应是什么意思?

本轮牛市还能持续多久?|疑问解答 2021-05-11

Binary tree - 617. Merge binary tree

【论文笔记】—目标姿态估计—EPro-PnP—2022-CVPR

Representation and implementation of stack (C language)

Matlab makes the image of serial port output data in real time

"Demons dance", is the bull market over? 2021-05-13

Bond network card mode configuration
随机推荐
Leetcode shahutong series -- 63. Different paths II
Backtracking - 17. Letter combinations of phone numbers
Packet switching and label switching in MPLS
LDP相关知识
寻找命令find和locate
用了MQ消息中间件后,我开始后悔了...
一个List到底能存多大的数据呢?
Detailed explanation of C language preprocessing
Binary tree -- 257. All paths of binary tree
对“DOF: A Demand-oriented Framework for ImageDenoising“的理解
Thymeleaf view integration
NVIDIA programmable reasoning accelerator tensorrt learning notes (III) -- Accelerating reasoning
Pinduoduo gets the usage instructions of the product details API according to the ID
markdown写作平台
MPLS中的包交换和标签交换
本轮牛市还能持续多久?|疑问解答 2021-05-11
【Redis】① Redis 的介绍、Redis 的安装
CountDownLatch
Binary tree - 530. Minimum absolute difference of binary search tree
After using MQ message oriented middleware, I began to regret