Django--FBV + CBV
发布时间:2020-12-20 10:56:02 所属栏目:Python 来源:网络整理
导读:目录 FBV + CBV FBV(function bases views) FBV中加装饰器相关 CBV(class bases views) CBV中加装饰器相关 FBV + CBV django中请求处理方式有2种:FBV 和 CBV FBV(function bases views) 就是在视图里使用函数处理请求,如下: # urls.pyfrom django.conf.urls
|
目录
FBV + CBVdjango中请求处理方式有2种:FBV 和 CBV FBV(function bases views)就是在视图里使用函数处理请求,如下: # urls.py
from django.conf.urls import url,include
from app01 import views
urlpatterns = [
url(r'^index/',views.index),]
# views.py
from 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
@deco
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')
上面就是FBV的使用。 CBV(class bases views)就是在视图里使用类处理请求,如下: # urls.py
from app01 import views
urlpatterns = [
url(r'^index/',views.Index.as_view()),]
# views.py
from 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装饰器,有以下三种方式:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
