django 视图中使用装饰器
写一个装饰器
import time def timer(fn): def inner(*args, **kwargs): start = time.time() ret = fn(*args, **kwargs) print("函数执行时间是{}".format(time.time() - start)) return ret return inner
FBV
# 添加出版社的处理函数 @timer def add_press(request): if request.method == 'POST': # 表示用户填写完了,要给我发数据 # 1. 取到用户填写的出版社数据 press_name = request.POST.get('name') # 2. 将数据添加到数据库中 Press.objects.create(name=press_name) # 3. 跳转到出版社列表页面 return redirect('/press_list/') # 1. 返回一个添加页面,让用户在上面填写新的出版社的信息 return render(request, 'add_press2.html')
CBV
from django.views import View from django.utils.decorators import method_decorator # @method_decorator(timer,name='post') # @method_decorator(timer,name='get') class AddPress(View): # http_method_names = ['get','post'] @method_decorator(timer) def dispatch(self, request, *args, **kwargs): print('执行之前') ret = super().dispatch(request, *args, **kwargs) print('执行之后') return ret # @method_decorator(timer) def get(self, request): print('get') print(self.request) return render(self.request, 'add_press2.html') # @method_decorator(timer) def post(self, request): print('post') press_name = request.POST.get('name') Press.objects.create(name=press_name) return redirect('/press_list/')
幻想毫无价值,计划渺如尘埃,目标不可能达到。这一切的一切毫无意义——除非我们付诸行动。