djangorestframework 登陆验证

两种验证方式:

  第一种:全局验证在视图中完成:

      位置

class authtication():
    def authenticate(self,request):
        token = request._request.GET.get("token")
        token_obj = models.UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed("用户认证失败")
        #认证通过(登陆通过 返回这两个)  源码
        return (token_obj.user, token_obj.token)
    # def authenticate_header(self,val):
    #     pass

    def authenticate_header(self, request):
        pass

  

 3、如果某些视图不需要验证则、

二、局部视图

  写在视图当中:


  

1、验证写在视图当中
class authtication():
    def authenticate(self,request):
        token = request._request.GET.get("token")
        token_obj = models.UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed("用户认证失败")
        #认证通过(登陆通过 返回这两个)  源码
        return (token_obj.user, token_obj.token)
    # def authenticate_header(self,val):
    #     pass

    def authenticate_header(self, request):
        pass

2、需要验证的时候直接进行验 authentication_classes = [authtication]
class OrderView(APIView):
    #认证可以加多个  可以在加一个认证类 authentication_classes = [authtication,authtication1]
    authentication_classes = [authtication]
    def get(self,request,*args,**kwargs):
        self.dispatch()
        # print("用户",request.user)
        # print("**", request.auth)

        ret = {"code":1000, "msg":None,"data":None}
        try:
            ret["data"] = ORDER_DICT
        except Exception as e:
            pass
        return JsonResponse(ret)
原文地址:https://www.cnblogs.com/yuanjia8888/p/15628014.html