需要在根目录下创建一个文件夹
里面写入代码
import jwt, time
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class UserMiddleware(MiddlewareMixin):
def process_request(self, request):
# 获取前台发送的信息
token = request.META.get('HTTP_TOKEN')
# 解密
try:
user = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')
# 判断是否过期
if user['exp'] < int(time.time()):
user = None
except:
user = None
# 在次插入给视图
request.META['USER'] = user
在配置项目
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware'
]