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))

總結

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: