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函数做一些自己想做的事情。

原文地址:https://www.cnblogs.com/wumingxiaoyao/p/6514239.html