标签:自己 key 系统 内容 handle res not 方式 ready
CBV(class base view),基于类的视图编程方式,即在view.py文件中使用类的方式为API接口书写对应的视图。与CBV对应的是FBV(function base view),基于函数的视图编程方式。
# 路由部分 from django.conf.urls import url,include from . import views urlpatterns = [ url(r‘^book/$‘,views.BookSerializers.as_view()), ] # 视图部分 class BookSerializers(View): def get(self,request): return HttpResponse("GET") def post(self,request): return HttpResponse("POST")
as_view部分
1 @classonlymethod 2 def as_view(cls, **initkwargs): 3 """ 4 Main entry point for a request-response process. 5 """ 6 for key in initkwargs: 7 if key in cls.http_method_names: 8 raise TypeError("You tried to pass in the %s method name as a " 9 "keyword argument to %s(). Don‘t do that." 10 % (key, cls.__name__)) 11 if not hasattr(cls, key): 12 raise TypeError("%s() received an invalid keyword %r. as_view " 13 "only accepts arguments that are already " 14 "attributes of the class." % (cls.__name__, key)) 15 16 def view(request, *args, **kwargs): 17 self = cls(**initkwargs) 18 if hasattr(self, ‘get‘) and not hasattr(self, ‘head‘): 19 self.head = self.get 20 self.request = request 21 self.args = args 22 self.kwargs = kwargs 23 #为捕获到异常,最后实际上就是执行dispatch()方法 24 return self.dispatch(request, *args, **kwargs) 25 view.view_class = cls 26 view.view_initkwargs = initkwargs 27 28 # take name and docstring from class 29 update_wrapper(view, cls, updated=()) 30 31 # and possible attributes set by decorators 32 # like csrf_exempt from dispatch 33 update_wrapper(view, cls.dispatch, assigned=()) 34 return view
dispatch部分
1 def dispatch(self, request, *args, **kwargs): 2 # Try to dispatch to the right method; if a method doesn‘t exist, 3 # defer to the error handler. Also defer to the error handler if the 4 # request method isn‘t on the approved list.
#根据请求的方法遍历http_method_names进行匹配,匹配成功返回子类的请求方法的方法名,供路由去执行该方法
5 if request.method.lower() in self.http_method_names: 6 handler = getattr(self, request.method.lower(), self.http_method_not_allowed) 7 else: 8 handler = self.http_method_not_allowed 9 return handler(request, *args, **kwargs)
是一个前后端分离的框架系统,使前、后端开发着可以脱离对方的工作,从而只考虑自己业务内容的代码逻辑的一个框架。
标签:自己 key 系统 内容 handle res not 方式 ready
原文地址:https://www.cnblogs.com/liuyinzhou/p/8746695.html