一 CBV与FBV

  • CBV:Class Based View
  • FBV:Function Based View
  • 之前写过的都是基于函数的view,就叫FBV。还可以把view写成基于类的,那就是CBV。

1.1 创建项目

root@darren-virtual-machine:~/PycharmProjects# django-admin startproject cbv_test

root@darren-virtual-machine:~/PycharmProjects# cd cbv_test/

root@darren-virtual-machine:~/PycharmProjects/cbv_test# python3 manage.py startapp app01

setting注册app

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
]

root@darren-virtual-machine:~/PycharmProjects/cbv_test# mkdir templates

root@darren-virtual-machine:~/PycharmProjects/cbv_test# vim cbv_test/settings.py

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,"templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

路由分发

from django.contrib import admin
from django.urls import path,include urlpatterns = [
path('admin/', admin.site.urls),
path('app01/',include(app01.urls)),
]

配置一个登录页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>用户登录</h3>
<form action="" method="POST">
{% csrf_token %}
<p>用户名:<input type="text" name="username"></p>
<p>密 码:<input type="password" name="password"></p>
<input type="submit">
</form> </body>
</html>

url文件

from django.urls import  path,re_path
from app01 import views urlpatterns = [
path('login/',views.login),
]

views视图文件

from django.shortcuts import render,redirect,HttpResponse

# Create your views here.
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request,"login.html")

访问

1.2 使用CBV改写

urls文件

from django.urls import  path,re_path
from app01 import views urlpatterns = [
path('login_fbv/',views.login),
path('login_cbv/', views.Login.as_view()),
]

views文件

from django.shortcuts import render,redirect,HttpResponse
from django.views import View # Create your views here.
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request,"login.html") #CBV
class Login(View):
def get(self,request):
return render(request, "login.html")
def post(self,request):
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request, "login.html")

访问http://127.0.0.1:8000/app01/login_cbv/登录

FBV本身就是一个函数,所以和给普通的函数加装饰器无差

1.3 使用装饰器装饰CBV

给CBV加装饰器

from django.shortcuts import render,redirect,HttpResponse
from django.views import View
import time # Create your views here. def timer(func):
def inner(request,*args,**kwargs):
start_time = time.time()
time.sleep(2)
rep = func(request,*args,**kwargs)
end_time = time.time()
print (end_time-start_time)
return rep
return inner #FBV
@timer
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request,"login.html")

1.4 使用装饰器装饰FBV

类中的方法与独立函数不完全相同,因此不能直接将函数装饰器应用于类中的方法 ,我们需要先将其转换为方法装饰器。Django中提供了method_decorator装饰器用于将函数装饰器转换为方法装饰器。

1.4.1 给某个方法加上装饰器

此例给get方法加上)

from django.shortcuts import render,redirect,HttpResponse
from django.views import View
import time
from django.utils.decorators import method_decorator
# Create your views here. def timer(func):
def inner(request,*args,**kwargs):
start_time = time.time()
time.sleep(2)
rep = func(request,*args,**kwargs)
end_time = time.time()
print (end_time-start_time)
return rep
return inner #FBV
@timer
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request,"login.html") #CBV
class Login(View):
@method_decorator(timer)
def get(self,request):
return render(request, "login.html")
def post(self,request):
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request, "login.html")

访问http://127.0.0.1:8000/app01/login_cbv/,只有get有,post并没有用到装饰器

[10/Apr/2020 11:27:53] "GET /app01/login_cbv HTTP/1.1" 301 0
2.024909496307373
[10/Apr/2020 11:27:55] "GET /app01/login_cbv/ HTTP/1.1" 200 456
[10/Apr/2020 11:28:05] "POST /app01/login_cbv/ HTTP/1.1" 200 16

1.4.2 加在dispatch方法上面

会给类下的所有方法加上此装饰器

from django.shortcuts import render,redirect,HttpResponse
from django.views import View
import time
from django.utils.decorators import method_decorator
# Create your views here. def timer(func):
def inner(request,*args,**kwargs):
start_time = time.time()
time.sleep(2)
rep = func(request,*args,**kwargs)
end_time = time.time()
print (end_time-start_time)
return rep
return inner #FBV
@timer
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request,"login.html") #CBV
class Login(View):
@method_decorator(timer)
def dispatch(self, request, *args, **kwargs):
obj = super().dispatch(request,*args,**kwargs)
return obj #这里必须返回,否则Httpresponse错误
#@method_decorator(timer)
def get(self,request):
return render(request, "login.html")
def post(self,request):
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request, "login.html")

访问http://127.0.0.1:8000/app01/login_cbv

[10/Apr/2020 11:35:08] "GET /app01/login_cbv/ HTTP/1.1" 200 456
2.01680588722229
2.00297474861145
[10/Apr/2020 11:35:16] "POST /app01/login_cbv/ HTTP/1.1" 200 16

1.4.3加在类上面

from django.shortcuts import render,redirect,HttpResponse
from django.views import View
import time
from django.utils.decorators import method_decorator
# Create your views here. def timer(func):
def inner(request,*args,**kwargs):
start_time = time.time()
time.sleep(2)
rep = func(request,*args,**kwargs)
end_time = time.time()
print (end_time-start_time)
return rep
return inner #FBV
@timer
def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request,"login.html") #CBV
@method_decorator(timer,name="get")
#如果需要给post方法家装饰器,method_decorator(timer,nmae="post"),必须制定name的值,否则报错

class Login(View):
#@method_decorator(timer)
def dispatch(self, request, *args, **kwargs):
obj = super().dispatch(request,*args,**kwargs)
return obj #这里必须返回,否则Httpresponse错误
#@method_decorator(timer)
def get(self,request):
return render(request, "login.html")
def post(self,request):
username = request.POST.get("username")
password = request.POST.get("password")
if username == "joy" and password == "123456":
return HttpResponse("login success...")
else:
return render(request, "login.html")

访问http://127.0.0.1:8000/app01/login_cbv/

2.017592191696167
[10/Apr/2020 11:39:04] "GET /app01/login_cbv/ HTTP/1.1" 200 456
[10/Apr/2020 11:39:10] "POST /app01/login_cbv/ HTTP/1.1" 200 16

在给类加装饰器的时候,也可以使用name=dispatch,也可以,关键是必须有这个类存在

062.Python前段框架Django视图CBV的更多相关文章

  1. python测试开发django-73.django视图 CBV 和 FBV

    前言 FBV(function base views) 就是在视图里使用函数处理请求,这一般是学django入门的时候开始使用的方式. CBV(class base views) 就是在视图里使用类处 ...

  2. 利用python web框架django实现py-faster-rcnn demo实例

    操作系统.编程环境及其他: window7  cpu  python2.7  pycharm5.0  django1.8x 说明:本blog是上一篇blog(http://www.cnblogs.co ...

  3. python 终极篇 --- django 视图系统

    Django的View(视图) 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 响应可以是一张网页的HTML内容,一个重定向,一个404错误, ...

  4. django视图 CBV 和 FBV

    目录 视图 CBV 和 FBV 什么是视图? FBV function based view 基于函数的视图 CBV class based view 基于类的视图 小技巧 CBV 如何获取页面请求类 ...

  5. python web框架Django入门

    Django 简介 背景及介绍 Django是一个开放源代码的Web应用框架,由Python写成.采用了MVC的框架模式,即模型M,视图V和控制器C.它最初是被开发来用于管理劳伦斯出版集团旗下的一些以 ...

  6. Django(视图 CBV、FBV)

    day67 参考:http://www.cnblogs.com/liwenzhou/articles/8305104.html CBV和FBV 我们之前写过的都是基于函数的view,就叫FBV.还可以 ...

  7. Python Web框架——Django

    返回顶部 使用框架简单快速开发特定的系统. pip freeze > requirements.txt pip install -r requirements.txt 一 MVC和MTV模式 二 ...

  8. python web框架 Django进阶

    django 进阶 基础中,一些操作都是手动创建连接的非主流操作,这样显得太low,当然也是为了熟悉这个框架! 实际中,django自带连接数据库和创建app的机制,同时还有更完善的路由系统机制.既然 ...

  9. python web框架 Django基本操作

    django 操作总结! django框架安装: cmd安装: pip3 install django pycharm安装: 在python变量下 搜索 django 安装 创建django项目: c ...

随机推荐

  1. Python基础(十八):面向对象“类”第一课

    记住:编写函数就是"面向过程",编写类就是"面向对象".类也是很多同学的一大学习难点,因此我这里还是准备带着大家学习一下. 类和对象对比 对象 : 具有行为和属 ...

  2. 结对编程_stage2

    项目 内容 这个作业属于哪个课程 2021春季软件工程(罗杰 任健) 这个作业的要求在哪里 结对项目-第二阶段 我在这个课程的目标是 从实践中学习软件工程相关知识(结构化分析和设计方法.敏捷开发方法. ...

  3. OO第三单元小结

    目录 JML理论基础 JML工具链 openjml使用 openjml总结 jmlunitng使用 代码分析 第一次作业 第二次作业 第三次作业 测试&bug分析 黑盒测试 白盒测试(Juni ...

  4. Unity2D项目-平台、解谜、战斗! 0.1 序言:团队、项目提出、初步设计、剧情大纲

    各位看官老爷们,这里是RuaiRuai工作室(以下简称RR社),一个做单机游戏的兴趣作坊. 本文跟大家聊一下社团内第一个游戏项目.算是从萌新项目组长的角度,从第一个里程碑的结点处,往前看总结一下项目之 ...

  5. JavaScript课程——Day01

    1.网页由三部分组成: 1.1.HTML:超文本标记语言,专门编写网页内容的语言.(结构) 1.2.CSS:层叠样式表.(样式) 1.3.javaScript:网页交互的解释性脚本语言,专门编写客户端 ...

  6. HashMap、ConcurrentHashMap 1.7和1.8对比

    本篇内容是学习的记录,可能会有所不足. 一:JDK1.7中的HashMap JDK1.7的hashMap是由数组 + 链表组成 /** 1 << 4,表示1,左移4位,变成10000,即1 ...

  7. 研发团队管理:IT研发中项目和产品原来区别那么大,项目级的项目是项目,产品级的项目是产品!!!

    前言   从事IT行业多年,一路从小杂兵成长为大团队Leader,对于研发整个体系比较清楚,其实大多人都经历过但是都忽略了的研发成本管控的一个关键的点就是研发过程中项目级和产品级的区别.   市场基本 ...

  8. 让我们一起建设 Vue DevUI 项目吧!🥳

    DevUI Design 是从华为云 DevCloud 众多业务孵化出来的一套设计体系,DevUI 倡导沉浸.灵活.至简的设计价值观,提倡设计者为真实的需求服务,为多数人进行设计,拒绝哗众取宠.取悦眼 ...

  9. D - 下个也是签到题 FZU - 2221(博弈)

    ZB loves watching RunningMan! There's a game in RunningMan called 100 vs 100. There are two teams, e ...

  10. 06- Linux Ubuntu下sublime下载与使用与安装包

    我有Linux下全套的安装包,如sublime,pycharm等.不用再苦逼的下软件了.需要的加我微信:chimu sublime text 3文本编辑器 启动命令:Linux命令行输入subl 或者 ...