django补充CBV和FBV模式

时间:2021-01-16 16:45:47
django补充CBV和FBV模式
FBV模式---函数:经常用的方式
CBV模式---类
CBV中url连接时函数名后面要接.as_view()
class index(views.View):
@...
def dispath(self,request,*arg,**kwarg):
super...
如果对某一种请求做处理:单一装饰器
如果对请求做处理:dispatch单一装饰器
注:CBV模式中的装饰器要调用method_decorator
from django.utils.decorators import method_decorator
在执行后台程序分辨get和post传值之前要先执行调用的view函数中的dispatch方法进行处理
例:
from django import views
from django.utils.decorators import method_decorator
def outer(func):
def inner(request,*args,**kwargs):
print(request.method)
return func(request,*args,**kwargs)
return inner #闭包
class Login(views.View):
message = ''
#分发器
def dispatch(self, request, *args, **kwargs):
print("eric")
req = super(Login,self).dispatch(request,*args,**kwargs)
print("ericc")
return req
@method_decorator(outer)
def get(self,request,*args,**kwargs):
return render(request,"login.html") @method_decorator(outer)
def post(self,request,*args,**kwargs):
user = request.POST.get("user")
pwd = request.POST.get("pwd")
c=1#数据库取值对照
if c:
request.session["is_login"] = True
request.session["username"] = user
req=redirect("/login/")
return req
else:
message = "用户名或密码错误"
return render(request,"login.html",{"msg":message})