FBV和CBV是个什么鬼?
FBC是基于Djandgo的function、base、view视图的 FBC的实现方式就是:
CBC就是基于类来实现的。
FBV的实现:
urls的配置:############ urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘login.html/‘,views.login), ] views的配置 ############# def login(request): return HttpResponse("ok") 浏览器输入127.0.0.1:8000/login.html的执行流程就是:一个path对应一个function
CBV的实现:
1:基于简单的get 和 post
####urls配置########### from frist import views urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘login.html/‘,views.Login.as_view()), ] ####views配置########## from django import views ##必须导入这个 class Login(views.View): def get(self,request,*args,**kwargs): return render(request,"login.html") def post(self,request,*args,**kwargs): username = request.POST.get("username") password = request.POST.get("password") return HttpResponse("your method post"+" "+username+" "+password) #####html_login配置######### <div> <form action="/login.html/" method="post"> <p>用户名:<input type="text" name="username"></p> <p>密码:<input type="password" name="password"></p> <p><input type="submit" value="提交"></p> </form> </div>
2:给CBV套上装饰器
from django.utils.decorators import method_decorator ###必须先导入
def outer(func): def inner(request,*args,**kwargs): print(request.method) return func(request,*args,**kwargs) ####记得return你的原函数 return inner class Login(views.View): def get(self,request,*args,**kwargs): return render(request,"login.html") @method_decorator(outer) def post(self,request,*args,**kwargs): username = request.POST.get("username") password = request.POST.get("password") return render(request,"index.html")
3:对与父类dispath的重新调用和装饰器
get和post方法是如何被调用的?????
实际上父类View中有一个dispatch方法,作用就是通过反射来调用子类的get和post方法。
请求先走dispatch,res就是get方法或者post方法执行只有的结果
所以这个请求的过程是:请求--->dispatch--->get/post
我们现在把dispatch写到子类中,继承父类的dispatch方法。dispatch写到子类或者单独写一个类,目的是根据需求加功能。
from django import viewsfromdjango.utils.decorators import method_decorator def outer(func): def inner(request,*args,**kwargs): print(request.method) return func(request,*args,**kwargs) return inner @method_decorator(Auth,name=‘dispatch‘) ###或者这样也是一样的都给每个加上装饰器,二者选一个
class Login(views.View): def get(self,request,*args,**kwargs): return render(request,"login.html") @method_decorator(Auth) ### ###可以在这个位置加装饰器,这就默认给每个方法都加上了装饰器了 def dispatch(self, request, *args, **kwargs): print(11111) res = super(Login,self).dispatch(request,*args,**kwargs) print(2222) return res def post(self,request,*args,**kwargs): username = request.POST.get("username") password = request.POST.get("password") return render(request,"index.html")