视图函数中加上认证功能,流程见下图
import hashlib
import time
def get_random(name):
md = hashlib.md5()
md.update(bytes(str(time.time()),encoding='utf-8'))
md.update(bytes(name,encoding='utf-8'))
return md.hexdigest()
from rest_framework.views import APIView
class Login(APIView):
authentication_classes = [AuthLogin]
def post(self, request, *args, **kwargs):
response = {'status': 100, 'msg': None}
name = request.data.get('name')
pwd = request.data.get('pwd')
user = models.User.objects.filter(name=name, password=pwd).first()
if user:
response['msg'] = '登陆成功'
# 随机字符串可以是用户名加当前时间生成的mds
token = get_random(name)
# 如果有记录,就只需要更新,不需要重新插入
# models.UserToken.objects.create(token=token,user=user)
# 查询 更新
# user_agent
models.UserToken.objects.update_or_create(user=user, defaults={'token': token})
response['token'] = token
else:
response['status'] = 101
response['msg'] = '用户名或密码错误'
return Response(response)
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import NotAuthenticated
from app01 import models
# BaseAuthentication
class AuthLogin(BaseAuthentication):
def authenticate(self, request):
# 封装后的request
token = request.GET.get('token')
# print(token)
ret = models.UserToken.objects.filter(token=token).first()
if ret:
return ret.user,token
else:
raise NotAuthenticated('您没有登陆')
在def initial(self, request, *args, **kwargs):函数中找到认证功能
流程总结:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。
Powered By python教程网 鲁ICP备18013710号
python博客 - 小白学python最友好的网站!