Django Rest Framework 源码解析

Django Rest Framework 源码解析

1、django-rest-framework源码中到处都是基于CBV和面向对象的封装;根据CBV的源码运行流程,还是执行dispatch()方法,只是rest framework插件 重写dispatch() 方法

rest_framework/views.py/APIView.dispatch()

 

def dispatch(self, request, *args, **kwargs):
    """
    `.dispatch()` is pretty much the same as Django's regular dispatch,
    but with extra hooks for startup, finalize, and exception handling.
    """
    self.args = args
    self.kwargs = kwargs
        
    ####################### 第一步 request二次封装 #######################     
    request = self.initialize_request(request, *args, **kwargs)
    self.request = request
    self.headers = self.default_response_headers  # deprecate?

    try:
        # 这里和原生的dispatch()基本一样
        # 重写了initial()方法
        # ####################### 第二步 初始化 #######################
        self.initial(request, *args, **kwargs)
            
        # Get the appropriate handler method
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(),
                              self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed

        response = handler(request, *args, **kwargs)

    except Exception as exc:
        response = self.handle_exception(exc)

    self.response = self.finalize_response(request, response, *args, **kwargs)
    return self.response

 2、通过initialize_request()方法扩展request,重新新封装了原生request、parsers(解析对象列表)authenticators(认证对象列表)

def initialize_request(self, request, *args, **kwargs):
    """
    Returns the initial request object.
    """
    parser_context = self.get_parser_context(request)

    return Request(
        request,
        # 解析相关 对象列表
        parsers=self.get_parsers(),
        # 认证相关 对象列表
        authenticators=self.get_authenticators(),
        # 选择相关 选择对象
        negotiator=self.get_content_negotiator(),
        # 解析内容
        parser_context=parser_context
    )

3、get_authenticators()方法找到setting中指定的认证类,或者在View中重写的认证类

def get_authenticators(self):
    """
    Instantiates and returns the list of authenticators that this view can use.
    """
    # 列表生成式,生成了相应的类的对象的列表:[对象,对象,...]
    return [auth() for auth in self.authentication_classes]
class APIView(View):

    # The following policies may be set at either globally, or per-view.
    # 下面的策略 可能在setting中设置,或者重写在每个View中
    renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
    parser_classes = api_settings.DEFAULT_PARSER_CLASSES
    authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
    throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
    permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
    content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
    metadata_class = api_settings.DEFAULT_METADATA_CLASS
    versioning_class = api_settings.DEFAULT_VERSIONING_CLASS

    # Allow dependency injection of other settings to make testing easier.
    settings = api_settings
    .....

4、回到dispatch()方法,在重新扩展封装了新的request之后,使用了 initial() 方法,初始化。在初始化的方法中,执行了认证、鉴权、限流这三个方法

def initial(self, request, *args, **kwargs):
    """
    Runs anything that needs to occur prior to calling the method handler.
    """
    self.format_kwarg = self.get_format_suffix(**kwargs)

    # Perform content negotiation and store the accepted info on the request
    neg = self.perform_content_negotiation(request)
    request.accepted_renderer, request.accepted_media_type = neg

    # Determine the API version, if versioning is in use.
    # 版本号,检查版本的对象
    version, scheme = self.determine_version(request, *args, **kwargs)
    request.version, request.versioning_scheme = version, scheme

    # Ensure that the incoming request is permitted
    # 认证
    self.perform_authentication(request)
    # 检查权限
    self.check_permissions(request)
    # 检查限制访问
    self.check_throttles(request)

 

 

 

你可能感兴趣的:(Django)