一. 背景
最近几天一直在学习restful framework的源代码,用户请求的流程,在路由系统这块遇到一个疑问,关于类的继承关系,当请求进来到路由这块,执行as_view()方法的时候,为什么会运行父类View的as_view()方法再执行到APIView的dispatch方法呢?这里记录一下一遍后面方便自己查阅
二. 代码示例
1. 路由
from django.conf.urls import url from api import views as api_view urlpatterns = [ url(r‘^index/‘, api_view.IndexView.as_view()), ]
2. 视图类
from rest_framework.response import Response from rest_framework.views import APIView class IndexView(APIView): def get(self,request): return Response(‘...‘)
三. 源代码分析
a. APIView的as_view方法
class APIView(View): @classmethod def 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_evaluation view = super(APIView, cls).as_view(**initkwargs) # 这里是继承了父类的方法as_view() view.cls = cls view.initkwargs = initkwargs return csrf_exempt(view)
# 代码太多只截取部分代码
b. super(APIView,cls).as_view(**initkwargs)执行了什么操作
# super(APIView,self) 首先找到 APIView的父类(就是类 View),然后把View类的as_view属性 转换为类 APIView的属性 # 相当于将View中的as_view()中的代码复制到API_View中的as_view中
所以最终运行 super(APIView,cls).as_view(**initkwargs)执行了View中的as_view方法
class View(object): http_method_names = [‘get‘, ‘post‘, ‘put‘, ‘patch‘, ‘delete‘, ‘head‘, ‘options‘, ‘trace‘] def __init__(self, **kwargs): for key, value in six.iteritems(kwargs): setattr(self, key, value) @classonlymethod def as_view(cls, **initkwargs): for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don‘t do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) if hasattr(self, ‘get‘) and not hasattr(self, ‘head‘): self.head = self.get self.request = request self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs) # 运行这里吧最后执行了self.dispatch view.view_class = cls view.view_initkwargs = initkwargs update_wrapper(view, cls, updated=()) update_wrapper(view, cls.dispatch, assigned=()) return view # 返回了view函数
原文地址:https://www.cnblogs.com/supery007/p/8432324.html
时间: 2024-11-06 12:29:27