一 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)
来源: http://www.bubuko.com/infodetail-2607158.html