Django中的CBV和FBV示例介绍

yipeiwu_com7年前Python基础

前言

本文主要给大家介绍了关于Django中CBV和FBV的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

一、  CBV

CBV是采用面向对象的方法写视图文件。

CBV的执行流程:

浏览器向服务器端发送请求,服务器端的urls.py根据请求匹配url,找到要执行的视图类,执行dispatch方法区分出是POST请求还是GET请求,执行views.py对应类中的POST方法或GET方法。

使用实例:

urls.py

path('login/',views.Login.as_view())

views.py

from django import views #在views.py的基础上添加
class Login(views.Views):
 def get(self,request)
  pass
  def pass(self,request)
  pass

使用装饰器:

from django import views
from django.utils.decorators import method_decorator
def outer(func):
 def inner(request,*args,**kwargs):
 return func(request,*args,**kwargs)
 return inner
class Login(views.View):
 @method_decorator(outer)
 def get(self,request,*args,**kwargs):
 pass

在类上面加装饰器,和在函数上加装饰器是一个性质。但加的方法有所不同。

eg:

@method_decorator(outer,name='dispatch')
class Login(views.View):

自定义dispatch:

class Login(views.View):
 def dispatch(self, request, *args, **kwargs):
 print(2222)
 ret = super(Login, self).dispatch(request, *args, **kwargs)
 print(1111)
 return ret
def get(self, request, *args, **kwargs):
  print('GET')
  return HttpResponse('OK')

执行结果:2222

  GET
  1111

二、    FBV

FBV即在views.py中以函数的形式写视图。

看代码:

urls.py

from django.conf.urls import url, include
# from django.contrib import admin
from mytest import views
 
urlpatterns = [
 # url(r‘^admin/‘, admin.site.urls),
 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的使用。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

对python 读取线的shp文件实例详解

如下所示: import shapefile sf = shapefile.Reader("E:\\1.2\\cs\\DX_CSL.shp") shapes = sf.shapes(...

使用Python的datetime库处理时间(RPA流程)

RPA流程自动化过程中,遇到时间的相关操作时,可以调用datetime库的一些方法进行处理。 datetime 是 Python 处理日期和时间的标准库。 1、获取当前日期和时间 我们先...

Python定时器实例代码

在实际应用中,我们经常需要使用定时器去触发一些事件。Python中通过线程实现定时器timer,其使用非常简单。看示例: import threading def fun_timer...

Python3 单行多行万能正则匹配方法

可匹配单行,也支持换行匹配 [\s\S]*? 加上括号,效果更好 ([\s\S]*?) 以上这篇Python3 单行多行万能正则匹配方法就是小编分享给大家的全部内容了,希...

TensorFlow高效读取数据的方法示例

概述 最新上传的mcnn中有完整的数据读写示例,可以参考。 关于Tensorflow读取数据,官网给出了三种方法: 供给数据(Feeding): 在TensorFlow程序运行的每...