认证组件

看源码

默认的认证流程(如图所示)

property属性函数能:

  • 1.将类转换为只读属性
  • 2.重新实现一个属性的setter和getter方法

执行流程

起始:认证组件是在用request.data的时候触发的

局部视图认证

from rest_framework.views import APIView
from django.http import JsonResponse
from rest_framework.authentication import BaseAuthentication
from app01.models import *
from rest_framework.exceptions import AuthenticationFailed
import hashlib, time

# 继承BaseAuthentication
class Authentication(BaseAuthentication):
	# Request类下的_authentication方法有认证组件的核心代码
    # 要求在自定义的认证类里必须有authenticate方法
    def authenticate(self,request):
        token=request._request.GET.get("token")
        token_obj=UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed("验证失败!")
        return (token_obj.user,token_obj)

def get_random_str(user):
    import hashlib,time
    ctime=str(time.time())
    md5=hashlib.md5(bytes(user,encoding="utf8"))
    md5.update(bytes(ctime,encoding="utf8"))
    return md5.hexdigest()


class LoginViewSet(APIView):
    authentication_classes = [Authentication,]
    def post(self,request,*args,**kwargs):
        res={"code":1000,"msg":None}
        try:
            user=request._request.POST.get("user")
            pwd=request._request.POST.get("pwd")
            user_obj=UserInfo.objects.filter(user=user,pwd=pwd).first()
            print(user,pwd,user_obj)
            if not user_obj:
                res["code"]=1001
                res["msg"]="用户名或者密码错误"
            else:
                token=get_random_str(user)
				# 有该记录就更新,如果没有就添加一条记录
UserToken.objects.update_or_create(user=user_obj,defaults={"token":token})
                res["token"]=token
        except Exception as e:
            res["code"]=1002
            res["msg"]=e

        return JsonResponse(res,json_dumps_params={"ensure_ascii":False})

全局视图认证组件

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",]
}
posted @ 2018-08-06 20:16  桥前石头  阅读(93)  评论(0编辑  收藏  举报