zoukankan      html  css  js  c++  java
  • doraemon的python CBV和FBV、视图装饰器

    ### 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)
    
    ```
  • 相关阅读:
    WEB前端:05_scroll滚动(图片/文字滚动)
    WEB前端:04_slider幻灯片(焦点图轮换)
    WEB前端:03_hover切换(显示/隐藏)
    概率统计
    概率统计
    线性代数
    线性代数
    线性代数
    线性代数
    大数据时代,Java通过JFreeChart分析和可视化数据
  • 原文地址:https://www.cnblogs.com/doraemon548542/p/11609128.html
Copyright © 2011-2022 走看看