1.生成token
1.需要安装jwt
pip install pyjwt
2.封装token生成方法
import time
import jwt # pip install pyjwt
from flask import current_app
class JwtTool():
'''
jwt管理
'''
def create(self,payload,ex=3600):
'''
生成jwt
:param payload: 载荷
:return: string jwt
'''
payload["exp"] = int(time.time())+ ex # 默认有效期1小时
secret_key = current_app.config.get("SECRET_KEY")
token = jwt.encode(payload,secret_key,algorithm="HS256")
return token
def valid(self,token):
'''
校验jwt
:param token: JWT
:return: 返回payload
'''
secret_key = current_app.config.get("SECRET_KEY")
try:
payload = jwt.decode(token, secret_key, algorithms="HS256")
return payload
except Exception as e:
print(e)
return False
settings/secretconfig.py
class SecretConfig():
RL_ACC_ID = "8a216da88185a9c001818a7781bc0148"
RL_ACC_TOKEN = "c98c0ae0fbc54e4da1a070db3050e529"
RL_APP_ID = "8a216da88185a9c001818a7782bf014f"
RL_TID = "1"
REDIS_HOST = "127.0.0.1"
REDIS_PORT =6379
其中SECRET_KEY是中配置项内获取需要写入配置项
SecretConfig是继承与短信验证码所需配置
settings/secret.py
from settings.secret import SecretConfig
class DefaultConfig(SecretConfig):
SECRET_KEY = "asdaweq"
SQLALCHEMY_DATABASE_URI=""
SQLALCHEMY_TRACK_MODIFICATIONS=False
SQLALCHEMY_ECHO=True
JSON_AS_ASCII=False
SMS_TIME = 5
class DevConfig(DefaultConfig):
SQLALCHEMY_DATABASE_URI="mysql+pymysql://root:password@127.0.0.1:3306/h2111anews"
2.发送短信验证码
import time
import jwt # pip install pyjwt
from flask import current_app
class JwtTool():
'''
jwt管理
'''
def create(self,payload,ex=3600):
'''
生成jwt
:param payload: 载荷
:return: string jwt
'''
payload["exp"] = int(time.time())+ ex # 默认有效期1小时
secret_key = current_app.config.get("SECRET_KEY")
token = jwt.encode(payload,secret_key,algorithm="HS256")
return token
def valid(self,token):
'''
校验jwt
:param token: JWT
:return: 返回payload
'''
secret_key = current_app.config.get("SECRET_KEY")
try:
payload = jwt.decode(token, secret_key, algorithms="HS256")
return payload
except Exception as e:
print(e)
return False
使用发送短信导入此类调用即可