目录
FBV + CBV FBV(function bases views) FBV中加装饰器相关 CBV(class bases views) CBV中加装饰器相关 FBV + CBVdjango中请求处理方式有2种:FBV 和 CBV
FBV(function bases vIEws)就是在视图里使用函数处理请求,如下:
# urls.pyfrom django.conf.urls import url,includefrom app01 import vIEws urlpatterns = [ url(r'^index/',vIEws.index),]
# vIEws.pyfrom django.shortcuts import render def index(req): if req.method == 'POST': print('method is :' + req.method) elif req.method == 'GET': print('method is :' + req.method) return render(req,'index.HTML')
注意此处定义的是函数【def index(req):】
<!--index.HTML--><!DOCTYPE HTML><HTML lang="en"><head> <Meta charset="UTF-8"> <Title>index</Title></head><body> <form action="" method="post"> <input type="text" name="A" /> <input type="submit" name="b" value="提交" /> </form></body></HTML>FBV中加装饰器相关
def deco(func): def wapper(request,*agrs,**kwargs): if request.cookieS.get('LOGIN'): return func(request,*args,**kwargs) return redirect('/login/') return wrapper@decodef index(req): if req.method == 'POST': print('method is :' + req.method) elif req.method == 'GET': print('method is :' + req.method) return render(req,'index.HTML')
上面就是FBV的使用。
CBV(class bases vIEws)就是在视图里使用类处理请求,如下:
# urls.pyfrom app01 import vIEws urlpatterns = [ url(r'^index/',vIEws.Index.as_vIEw()),]
# vIEws.pyfrom django.vIEws import VIEw # 类要继承VIEw ,类中函数名必须小写class Index(VIEw): def get(self,req): ''' 处理GET请求 ''' print('method is :' + req.method) return render(req,'index.HTML') def post(self,req): ''' 处理POST请求 ''' print('method is :' + req.method) return render(req,'index.HTML')CBV中加装饰器相关
要在CBV视图中使用我们上面的check_login装饰器,有以下三种方式:
加在CBV视图的get或post方法上
from django.utils.decorators import method_decoratorfrom django.vIEws import VIEwclass Index(VIEw): def dispatch(self,req,**kwargs): return super(Index,self).dispatch(req,**kwargs) def get(self,req): print('method is :' + req.method) return render(req,'index.HTML') @method_decorator(deco) def post(self,'index.HTML')
加在diapatch方法上,因为CBV中首先执行的就是dispatch方法,所以这么写相当于给get和post方法都加上了登录校验。
from django.utils.decorators import method_decoratorfrom django.vIEws import VIEwclass Index(VIEw): @method_decorator(deco) def dispatch(self,'index.HTML') def post(self,'index.HTML')
直接加在视图类上,但method_decorator必须传name关键字参数
如果get方法和post方法都需要登录校验的话就写两个装饰器
from django.utils.decorators import method_decoratorfrom django.vIEws import VIEw@method_decorator(deco,name='get')@method_decorator(deco,name='post')class Index(VIEw): def dispatch(self,'index.HTML')总结
以上是内存溢出为你收集整理的Django--FBV + CBV全部内容,希望文章能够帮你解决Django--FBV + CBV所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)