您的当前位置:首页正文

drf——认证、权限、频率源码分析、全局异常处理、自动生成接口文档、RBAC介绍

2024-11-29 来源:个人技术集锦

系列文章目录

drf



一、认证源码分析

所有视图都是基于APIView

class APIView(View):
	# 获取认证配置
	authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
	# 
	settings = api_settings

然后APIView的as_view会运行dispatch方法

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

        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
        	# 在此处运行了initial来处理认证
            self.initial(request, *args, **kwargs)
        return self.response

initial方法运行perform_authentication

    def initial(self, request, *args, **kwargs):
        self.format_kwarg = self.get_format_suffix(**kwargs)
        neg = self.perform_content_negotiation(request)
        request.accepted_renderer, request.accepted_media_type = neg
        version, scheme = self.determine_version(request, *args, **kwargs)
        request.version, request.versioning_scheme = version, scheme
        #此处运行认证相关方法
        self.perform_authentication(request)
        self.check_permissions(request)
        self.check_throttles(request)

perform_authentication将传入的user进行验证

    def perform_authentication(self, request):
        request.user

request的user将会进行登录认证

    def __init__(self, request, parsers=None, authenticators=None,
                 negotiator=None, parser_context=None):
        assert isinstance(request, HttpRequest), (
            'The `request` argument must be an instance of '
            '`django.http.HttpRequest`, not `{}.{}`.'
            .format(request.__class__.__module__, request.__class__.__name__)
        )

        self._request = request
        self.parsers = parsers or ()
        self.authenticators = authenticators or ()
        self.negotiator =
显示全文