参考官方文档:https://pyjwt.readthedocs.io/en/latest/
基本的加密和解密
import jwt
encoded_jwt = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")
print(encoded_jwt)
print(jwt.decode(encoded_jwt, "secret", algorithms=["HS256"]))
基本的封装
import jwt
def get_jwt(data, secret="zhangdapeng520", algorithm="HS256"):
if not isinstance(data, dict):
return None
return jwt.encode(data, secret, algorithm=algorithm)
def parse_jwt(data, secret="zhangdapeng520", algorithm="HS256"):
if not isinstance(data, str):
return None
return jwt.decode(data, secret, algorithms=[algorithm])
if __name__ == '__main__':
data = {"some": "payload"}
token = get_jwt(data)
print(token)
data2 = parse_jwt(token)
print(data2)