### 11.7 FBV和CBV #### 11.7.1 CBV的使用 FBC: function based view CBV:class based view 定义CBV: ```python from django.views import View class AdddPublisher(View): def get(self,request): """处理get请求""" return response def post(self,request): """处理post请求""" return response ``` 使用CBV ```python #在urls这个文件夹中使用 url(r‘^add_publisher/‘,views.AddPublisher.as_view()) ``` #### 11.7.2 as_view的流程 1. 项目启动 加载url.py时,实行类.as_view()-------->view函数 2. 请求到来的时候执行view函数; 1. 实例化--------->self--------->self.request=request 2. 执行self.dispatch(request,*args,**kwargs 1. 判断请求方式是否被允许 2. 允许 通过发射获取到对应请求当时 ---->handler 3. 不予许 self.http_mothod_not_allowed--------->handler 4. 执行handler(request,*args,**kwargs) 5. #### 11.7.3 视图加装饰器 FBV 直接加装饰器 CBV ```python from django.utils.decorators import method_decorator ``` 1.加在方法上 ```python @method_decorator(timer) def get(self,request,*args,**kwargs): pass ``` 2.加载dicpatch方法上 ```python @method_decorator(timer) def dispatch(self,request,*args,**kwargs): #print(‘before‘) ret = super().deipatch(request,*args,**kwargs) #print(‘after‘) return ret @method_decorator(timer,name = ‘dispatch‘) class AddPublisher(View): ``` 3.加载类上 ```python @method_decorator(timer,name=‘post‘) @method_decorator(timer,name=‘get‘) class AddPublisher(View): ``` #### 11.7.4request对象 ```python #属性 request.method 请求方式 request.GET url上携带的参数 resquest.POST post请求提交的数据 request.path_info URL的路劲 不包含ip和端口 不包含参数 request.body 请求体 b‘‘ request.FILES 上传的文件 request.META 请求头 request.COOKIES cokkies request.session session #方法 request.get_full_path() URL的路劲 不包含ip和端口 不包含参数 request.is_ajax() 判断是否是ajax请求 ``` #### 11.7.5 response对象 ```python from django.shortcuts import render,redirect,HttpResponse HttpResponse(‘字符串‘) render(request,‘模板的名称‘,{k1:v1}) redirect(‘重定向的地址‘) # HttpResponse如果要传非字典的东西 from django.shortcuts import HttpResponse JsonResponse({}) JsonResponse([].safe=False) ```
原文:https://www.cnblogs.com/doraemon548542/p/11609128.html