本文主要是介绍DRF——APIView源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
DRF——APIView源码解析
APIView源码分析
class task(APIView)
:直接Ctrl+左键进入APIView- 直接看里面的as_view()方法
class APIView(View): @classmethoddef as_view(cls, **initkwargs):if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):def force_evaluation():raise RuntimeError('Do not evaluate the `.queryset` attribute directly, ''as the result will be cached and reused between requests. ''Use `.all()` or call `.get_queryset()` instead.')cls.queryset._fetch_all = force_evaluationview = super().as_view(**initkwargs)view.cls = clsview.initkwargs = initkwargs# Note: session based authentication is explicitly CSRF validated,# all other authentication is CSRF exempt.return csrf_exempt(view)
- 当请求发送过来时先进入csrf_exempt(view)
def csrf_exempt(view_func):"""Mark a view function as being exempt from the CSRF view protection."""# view_func.csrf_exempt = True would also work, but decorators are nicer# if they don't have side effects, so return a new function.@wraps(view_func)def wrapper_view(*args, **kwargs):return view_func(*args, **kwargs)wrapper_view.csrf_exempt = Truereturn wrapper_view
- 里面其实就是第一个CSRF装饰器,它帮你免除了CSRF保护,并返回了一个带有相同功能的函数
view = super().as_view(**initkwargs)
:调用了父类的as_view(),也就是老的View类- 那么既然它既然调用了父类的方法,肯定也会有些地方进行了重新
- 老View中最重要的方法是什么?是dispatch
- 直接在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 = argsself.kwargs = kwargs# 1.这里包装了新的request对象,此时的request在原Django的request对象的基础上升级了request = self.initialize_request(request, *args, **kwargs)self.request = requestself.headers = self.default_response_headers # deprecate?try:# 2.initial里做了三件事:三大认证:认证,频率,权限self.initial(request, *args, **kwargs)# Get the appropriate handler method# 3.这里看注释也能猜到就是执行了跟请求方式同名的方法,也就是我们用的get post...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_allowedresponse = handler(request, *args, **kwargs)# 4.如果三大认证或者视图函数出现异常会在这里统一处理except Exception as exc:response = self.handle_exception(exc)self.response = self.finalize_response(request, response, *args, **kwargs)return self.response
- 先来看一下三大认证
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 requestneg = 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 permittedself.perform_authentication(request)self.check_permissions(request)self.check_throttles(request)
- self.perform_authentication(request) 验证请求合法性
- self.check_permissions(request) 检查请求权限
- self.check_throttles(request) 验证请求频率
总结:
- 只要执行了DRF的APIView,就不会再有CSRF限制了
- request也会被替换为它新建的request
- 在执行请求方法之前(与方法重名的request请求)进行了三大验证
- 验证合法性
- 验证请求权限
- 验证请求频率
- 三大认证和视图函数中任意位置出现异常统统报错
DRF的Request解析
先从结果出发,DRF的Request比Django的request多了个data属性
就是这个data属性帮我们序列化和反序列化,无需额外针对它的编码和请求方式进行修改判断
而这个新的request对象就是
from rest_framework.request import Request
这里的Request对象
老样子直接进他源码
class Request:
- 此时抛出第一个疑问:既然新Request没有继承老的request那他是怎么实现方法重构的呢?难不成一个一个写吗
- 其实它在下面用到了魔法方法
__getattr__
def __getattr__(self, attr):"""If an attribute does not exist on this instance, then we also attemptto proxy it to the underlying HttpRequest object."""try:_request = self.__getattribute__("_request")return getattr(_request, attr)except AttributeError:return self.__getattribute__(attr)
__getattr__
是一个拦截方法,当调用了类中不存在的属性时就会触发__getattr__
- _
request = self.__getattribute__("_request")
的意思就是通过调用对象的__getattribute__
方法来获取对象中名为_request
的属性值,说白了就是去老request中取属性 - 那么接下来在找找data属性在哪
request.data
直接进入data查看源码
- 注意是rest_framework.request的data
@property
def data(self):if not _hasattr(self, '_full_data'):self._load_data_and_files()return self._full_data
- 当前实例中没有_full_data属性时自动调用_load_data_and_files()方法,而这个方法就是他帮我们封装各种请求和编码方式的地方(内容过多有兴趣自己去了解)
总结:
- 之前如何用request,在DRF中还是如何用
- request.data将请求体的数据,将原先的各个方法包装成了数据属性
- request.query_params就是原先的request.GET,这么写是为了符合restful规范
__getattr__
中的request._request 就是老的Django中的request
魔法方法__getattr__
以__开头的都叫魔法方法,魔法方法不是我们主动调用的,而是在某种情况下自动触发的
__getattr__
用于拦截对象.属性,如果属性不存在则会触发
class Person:def __getattr__(self, item):print('根据:', item, '取值')return '123'p = Person()
print(p.name) # 属性不存在,就会打印__getattr__中的内容
# 根据: name 取值
# 123```python
class Person:def __getattr__(self, item):print('根据:', item, '取值')return '123'p = Person()
print(p.name) # 属性不存在,就会打印__getattr__中的内容
# 根据: name 取值
# 123
这篇关于DRF——APIView源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!