标签:查看 event ret 因此 code spl 扩展 log redirect
# FBV版添加班级 def add_class(request): if request.method == "POST": class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/") return render(request, "add_class.html")
# CBV版添加班级 from django.views import View class AddClass(View): def get(self, request): return render(request, "add_class.html") def post(self, request): class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/")
注意:
使用CBV时,urls.py中也做对应的修改:
# urls.py中 url(r‘^add_class/$‘, views.AddClass.as_view()),
def wrapper(func): def inner(*args, **kwargs): start_time = time.time() ret = func(*args, **kwargs) end_time = time.time() print("used:", end_time-start_time) return ret return inner # FBV版添加班级 @wrapper def add_class(request): if request.method == "POST": class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/") return render(request, "add_class.html")
类中的方法与独立函数不完全相同,因此不能直接将函数装饰器应用于类中的方法 ,我们需要先将其转换为方法装饰器。
Django中提供了method_decorator装饰器用于将函数装饰器转换为方法装饰器。
# CBV版添加班级 from django.views import View from django.utils.decorators import method_decorator class AddClass(View): @method_decorator(wrapper) def get(self, request): return render(request, "add_class.html") def post(self, request): class_name = request.POST.get("class_name") models.Classes.objects.create(name=class_name) return redirect("/class_list/")
# 使用CBV时要注意,请求过来后会先执行dispatch()这个方法,如果需要批量对具体的请求处理方法,如get,post等做一些操作的时候,这里我们可以手动改写dispatch方法,这个dispatch方法就和在FBV上加装饰器的效果一样。(可以从as_view()进去查看源码) class Login(View): def dispatch(self, request, *args, **kwargs): print(‘before‘) obj = super(Login,self).dispatch(request, *args, **kwargs) print(‘after‘) return obj def get(self,request): return render(request,‘login.html‘) def post(self,request): print(request.POST.get(‘user‘)) return HttpResponse(‘Login.post‘)
标签:查看 event ret 因此 code spl 扩展 log redirect
原文地址:https://www.cnblogs.com/wtil/p/11523328.html