django手撸系列-实现token功能
一. 需求
使用django实现token功能
二. 实现
第一步: 应用下或者项目下创建文件夹middleware
第二步: 在middleware文件夹下创建token_middle.py文件
第三步: 书写代码
import hashlib
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
def encryption(json_data):
md5_obj = hashlib.md5()
md5_obj.update(json_data.encode('utf-8'))
return md5_obj.hexdigest()
class TokenMiddle(MiddlewareMixin):
def process_request(self, request):
token_label = request.get_signed_cookie('token_id', default=None, salt='盐')
if token_label:
token, label = token_label.split('|')
current_label = encryption(token)
if label != current_label:
return HttpResponse('对不起, token_id不正确!')
request.token_auth = True
else:
request.token_auth = False
def process_response(self, request, response):
"""
响
"""
obj = response
if hasattr(request, 'user_obj'):
if request.user_obj:
token = json.dumps({'userID': request.user_obj.id}) # 拿到
label = encryption(token)
token_label = '|'.join([token, label])
obj.set_signed_cookie('token_id', token_label, salt='盐')
return response
第四步: settings.py文件中注册刚刚熟悉的中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 自定义注册中间价
'app01.middleware.my_middleware.TokenMiddle',
]