当前位置:网站首页>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)
边栏推荐
- 京东按关键字搜索商品 API 的使用说明
- 计算物理期刊修改
- Old laptop becomes server (laptop + intranet penetration)
- J9 number theory: what is Dao mode? Obstacles to the development of Dao
- Stack and queue - 150. Inverse Polish expression evaluation
- Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
- Detailed explanation of kubernetes network plug-ins - calico chapter - Overview
- Binary tree 101. Symmetric binary tree
- 网站服务器停止响应是什么意思?
- Jd.com API for obtaining recommended product list
猜你喜欢

Binary tree - 404. Sum of left leaves

J9 number theory: what is Dao mode? Obstacles to the development of Dao

Binary tree -- 104. Maximum depth of binary tree

Yolov4 tiny network structure

Stack and queue - 239. Sliding window maximum

bond网卡模式配置

牛市还将继续,拿好手里的币 2021-05-08

What does it mean that the web server stops responding?

Redirection and request forwarding

Js理解之路:写一个比较完美的组合继承(ES5)
随机推荐
多任务编程
牛市还没有结束,还有下半场 2021-05-18
FreeRTOS personal notes - mutex
Leetcode high frequency question 66. add one, give you an array to represent numbers, then add one to return the result
Thymeleaf view integration
寻找命令find和locate
Jd.com API for obtaining recommended product list
Binary tree -- 111. Minimum depth of binary tree
Backtracking - 77. combination
Getaverse,走向Web3的远方桥梁
Recent impressions about bull market and defi 2021-05-17
[hero planet July training leetcode problem solving daily] 25th tree array
Detailed explanation of kubernetes network plug-ins - calico chapter - Overview
FreeMarker view integration
MySQL——数据库日志
Use of redis
Hefei approved in advance
Linked list related methods
After using MQ message oriented middleware, I began to regret
Solid smart contract development - 3.2-solid syntax array, structure, mapping