前言:APIView基于View 看这部份内容必定要懂django—CBV里的内容python
在django—CBV源码分析中,咱们是分析的from django.views import View下的执行流程
这篇博客咱们就来了解下APIView是如何执行的,跟django.views模块下的view有何关联?
咱们依然从urls.py
配置入手分析django
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^publishes/', views.PublishView.as_view()), ]
views.py
json
from rest_framework.views import APIView class PublishView(APIView): def get(self,request): publish_list=Publish.objects.all() ret=serialize("json",publish_list) return HttpResponse(ret) def post(self,request): pass
一、首先咱们仍是来确认urls.py
中as_view
是谁执行的?
首先咱们去views.PublishView
中找,发现找不到,因此咱们接着再去PublishView
的父类APIView
中去找,找到了因此执行调用APIView.as_view()
,内容以下:api
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 # 1. super调用父类的as_view的执行结果赋值给view这个变量 view = super(APIView, cls).as_view(**initkwargs) view.cls = cls view.initkwargs = initkwargs # Note: session based authentication is explicitly CSRF validated, # all other authentication is CSRF exempt. # csrf_exempt 不在执行调用csrf_token那个中间件 # 中间件是针对全局的 # 2. 这里返回的view就是父类View.view return csrf_exempt(view)
二、你们是否是觉得这样就结束了?NO!NO!NO!
若是是as_view是View的as_view
,dispatch是View的dispatch
,那rest-framework
不就成废钞了么?
as_view的执行结果是dispatch的执行结果,那么dispatch仍是View的dispatch么?session
中间的这点代码跟以前的View.dispatch同样:
仍是作请求分发,在请求以外又作了一堆事情app
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)
url 转变过程iview
View.as_view()咱们在django—CBV讲解过了
因此最后调用仍是,只是APIView.as_view在里边加了一些他本身定义的一些东西,只是咱们没用到而已函数
APIView.as_view()---> View.as_view()---> APIView.dispatch()--->response--->handler()--> 本身定义请求方法函数的返回结果,不然就抛错405源码分析