python中封装token问题
来源:脚本之家    时间:2022-12-21 05:52:01


(相关资料图)

目录
python 封装token如何封装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))

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

关键词: 加密操作 加密密钥 希望大家 直接调用

上一篇:

下一篇:

X 关闭

X 关闭