这篇文章主要介绍了python如何封装token的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇python如何封装token文章都会有所收获,下面我们一起来看看吧。
python 封装token
import datetime
class MyJwt:
def __init__(self):
# 加密密钥
self.password = "1231231241234refd"
# 加密方法
def encode_jwt(self,userinfo):
# 加密操作
encode_srt = jwt.encode(userinfo,self.password,algorithm="HS256")
try:
encode_srt = str(encode_srt,"utf-8")
except Exception as e:
pass
return encode_srt
# 时常加密
# userinfo :用户信息
# mytime: 设置过期时间
def encode_jwt_t(self,userinfo,mytime):
playload = {
'exp': int((datetime.datetime.now()+datetime.timedelta(seconds=mytime)).timestamp()),
'data':userinfo
}
# 加密操作
encode_srt = jwt.encode(playload,self.password, algorithm="HS256")
try:
encode_srt = str(encode_srt, "utf-8")
except Exception as e:
pass
return encode_srt
# 解密
def decode_jwt(self,jwt_str):
return jwt.decode(jwt_str,self.password,algorithms=['HS256'])
如何封装token,直接调用
import jwt
import time
class JwtTool:
#生成token
def create_token(self, payload, ex):
a = "sss"
payload['ex'] = int(time.time()) + ex
try:
token = jwt.encode(payload, key=a)
print("生成token成功", token)
return token
except Exception as e:
print("生成token的错误", e)
return False
#解析token
def check_token(self, token):
try:
a = "sss"
payload = jwt.decode(token, key=a, algorithms="HS256")
print("解析token成功", payload)
return payload
except Exception as e:
print("解析token错误", e)
return False
#单独文件测试
if __name__ == '__main__':
from app import app
with app.app_context():
j = JwtTool()
payload = {
"ia": 1,
"name": "小米"
}
token = j.create_token(payload, 200)
print("-----", token)
# token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYSI6MSwibmFtZSI6Ilx1NWMwZlx1N2M3MyJ9.ru9-3H7Z9abbkKXkZMbekeAEdlE-COw9CASYMxIG728"
# print("++++",j.check_token(token))
版权声明:除特别声明外,本站所有文章皆是本站原创,转载请以超链接形式注明出处!