开发者

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(seljavascriptf,userinfo,mytime):
        plwww.devze.comayload = {
            '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("解析tokenphp成功", 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))

总结

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜