Django rest Framework(DRF)源码解析——as_view

一.请求流程

1.as_view函数

"""Main entry point for a request-response process."""
是请求响应API一个入口点,其一是创建了一个我们自定义类的实例,二是调用dispatch方法

View类里面有as_view函数,APIView里面也有as_view函数,APIView是对View类里面的重写,最终调用继承类的dispatch函数

 

2.dispatch函数

"""
`.dispatch()` is pretty much the same as Django's regular dispatch,but with extra hooks for startup, finalize, and exception handling.
"""
此函数主要用于Djangorequest的封装,认证权限流处理,请求方法的映射,使请求方法与CBV方式的函数对应

 

3. initialize_request函数
"""
Returns the initial request object.
"""
返回一个DRF下的Request类对象,即封装Django的request
除了封装原生Django的request,还有新增了解析器,认证对象类列表,里面对一些查询方式也做了修改,新的request.query_params 得到是旧的request.GET的值,可以使用request._request获取原生的请求等
 
4. initial函数
"""
Runs anything that needs to occur prior to calling the method handler.
"""
在执行视图函数方法之前,需要处理一些东西,比如版本控制,认证,权限,验证。处理完后才会进行方法映射。对应调用函数依次是
# Determine the API version, if versioning is in use.  # 决定API版本
determine_version
# Ensure that the incoming request is permitted   # 确保请求可以被允许
perform_authentication(request)
check_permissions(request)
check_throttles(request)
 
5.getattr函数
# Get the appropriate handler method
映射函数


posted @ 2021-05-07 18:49  落秋巴  阅读(100)  评论(0编辑  收藏  举报