3. DRF 认证

Django DRF 认证

1. 使用

1.1 设置认证全局变量

在settings.py添加如下代码


REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": ['utils.auth.Myauth']
}

1.2 为方法单独设置认证

views.py中添加 authentication_classes = [Myauth]


from utils.auth import Myauth
class Home2(APIView):
    authentication_classes = [Myauth]

    def get(self, reqeust):
        return JsonResponse({"status": True, 'data': 'OK'})

    def post(self, request):
        return JsonResponse({"status": True, 'data': 'OK'})

1.3 编写认证类

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
import json

class Myauth(BaseAuthentication):
    def authenticate(self, request):
        raise AuthenticationFailed({'status': False, 'detail': '登陆失败'})

1.4 案例

认证类会校验请求体中有没有token

2. 源码流程

上篇讲到所有通过drf的请求都会走到APIView,
执行时会执行这段代码
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES

因为api_settings类中没有定义DEFAULT_AUTHENTICATION_CLASSES,
所以执行api_settings.DEFAULT_AUTHENTICATION_CLASSES会走到APISetting类中的__getattr__方法

所以authentication_classes 如果用户定义就使用定义的值 要么就使用默认值

往下走到了drf中views.py的dispatch方法

精简代码, 进入self.initialize_request看发生了什么

    def dispatch(self, request, *args, **kwargs):

        request = self.initialize_request(request, *args, **kwargs)

        try:
            self.initial(request, *args, **kwargs)


			handler = getattr(self, request.method.lower(),
                        self.http_method_not_allowed)
			handler = self.http_method_not_allowed

现在知道了drf生成的新request里封装了 authenticators = [将每个authticator实例化]

以上就是 DRF 认证功能的全部内容

posted @ 2024-07-11 18:26  khalil12138  阅读(11)  评论(0编辑  收藏  举报