django 檢視中使用裝飾器
阿新 • • 發佈:2020-10-14
寫一個裝飾器
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/')