restframework api(基础3CBV)

一 CBV源码流程

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^order/', views.OrderView.as_view()),
]

  

view.py

from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
class OrderView(View):

    def get(self,request,*args,**kwargs):
        ret = {'code': 1000, 'msg': None, 'error': None}
        return JsonResponse(ret)

  

1)从上面的urls.py文件种可以看到,一个url对应了一个  这个views.OrderView.as_view()函数,并执行这个函数,也就是我们调用order的url会views.OrderView.as_view()()

2)从views.py文件种看到OrderView这个类种,并没有as_view()方法,所以需要到View类种找

    # 这是一个类方法
    @classonlymethod
    def as_view(cls, **initkwargs):
        """
        Main entry point for a request-response process.
        """
        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 = OrderView()
            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
            # handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
            # return handler(request, *args, **kwargs)
            # 这个as_view()返回了一个OrderView().dispatch(request, *args, **kwargs)方法
            # 这里返回了dispatch(),所以这个dispath方法会被执行,但是需要从头开始找起
            return self.dispatch(request, *args, **kwargs)
        view.view_class = cls
        view.view_initkwargs = initkwargs

        # take name and docstring from class
        update_wrapper(view, cls, updated=())

        # and possible attributes set by decorators
        # like csrf_exempt from dispatch
        update_wrapper(view, cls.dispatch, assigned=())
        # 由于调用url会views.OrderView.as_view()()所以,这里会执行view函数
        return view

    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        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
        # 最终返回了执行后的handler()
        return handler(request, *args, **kwargs)

  

原文地址:https://www.cnblogs.com/wanstack/p/9058012.html