Django中的CBV和FBV示例介绍

yipeiwu_com6年前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 pass 语句使用示例

Python pass是空语句,pass语句什么也不做,一般作为占位符或者创建占位程序,是为了保持程序结构的完整性,pass语句不会执行任何操作,比如: Python 语言 pass 语...

用python标准库difflib比较两份文件的异同详解

用python标准库difflib比较两份文件的异同详解

【需求背景】 有时候我们要对比两份配置文件是不是一样,或者比较两个文本是否异样,可以使用linux命令行工具diff a_file b_file,但是输出的结果读起来不是很友好。这时候使...

基于DataFrame改变列类型的方法

今天用numpy 的linalg.det()求矩阵的逆的过程中出现了一个错误: TypeError: No loop matching the specified signature...

python类中super()和__init__()的区别

单继承时super()和__init__()实现的功能是类似的 class Base(object): def __init__(self): print 'Base create'...

Python通过Django实现用户注册和邮箱验证功能代码

本文主要向大家分享了Python编程中通过Django模块实现用户注册以及邮箱验证功能的简单介绍及代码实现,具体如下。 用户注册: 类似于用户登陆,同样在users.views.py中添...