1. 程式人生 > >restframework api(基礎3CBV)

restframework api(基礎3CBV)

__name__ AS lasso ocs http HA resp bsp init

一 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)

  

restframework api(基礎3CBV)