zoukankan      html  css  js  c++  java
  • CBV中的dispatch

    之前介绍了FBV和CBV ,下面我们看一下CBV中的dispatch 

    dispatch函数在类View中定义,作用就是通过反射查找get或post函数,所以在执行get或post函数之前,dispatch函数是肯定会被执行的。因此我们可以通过super,来重写dispatch,达到一个类似装饰器的功能。
    views.py
    from django.shortcuts import render
    from django.views import View
    
    
    class Index(View):
    
        def dispatch(self, request, *args, **kwargs):
            print('Before')
            ret = super(Index, self).dispatch(request, *args, **kwargs)
            print('After')
            return ret
    
        def get(self, req):
            print('method is :' + req.method)
            return render(req, 'index.html')
    
        def post(self, req):
            print('method is :' + req.method)
            return render(req, 'index.html')
    

      

    后台输出:

    Before
    method is :GET
    After
    Before
    method is :POST
    After

    可见,我们可以在执行get或者post函数时,通过dispatch函数做一些自己想做的事情。

  • 相关阅读:
    jenkins持续集成
    对pm2对研究
    模板⽅法模式
    python configparser模块
    Python正则表达式
    Python读写文件之换行符
    Python字符串
    Python字典
    Python列表
    爬虫 urllib,requests,lxml,bs4 小结
  • 原文地址:https://www.cnblogs.com/wumingxiaoyao/p/6514239.html
Copyright © 2011-2022 走看看