可以用在多个框架当中,不需要再使用一个框架就使用框架拓展的jwt模块
jwt.py代码
# jwt万能类
import jwt
import datetime
from .settings import SECRET_KEY
# from apps.user.models import User
class JwtClass(object):
# 加密token
def create_token(self, user_number):
'''
加密token
:param user_number:
:return:
'''
if user_number:
try:
# 过期时间为一天
token = jwt.encode(
{
'user_number': user_number,
'exp': datetime.datetime.now() + datetime.timedelta(days=1)
},
key=SECRET_KEY, algorithm='HS256'
)
except Exception as err:
print(err)
return None
return token
else:
return None
# 解密token
def check_token(self, token):
'''
解密token
:param token:
:return:
'''
if token:
try:
data = jwt.decode(token, key=SECRET_KEY, algorithms=['HS256'])
user_number = data['user_number']
except Exception as err:
print(err)
print('解密失败')
return None
else:
if User.objects.filter(user_number=user_number):
return user_number
else:
return None
else:
return None