Django中的CBV和FBV示例介绍

yipeiwu_com5年前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的Django框架中编写编译函数

当遇到一个模板标签(template tag)时,模板解析器就会把标签包含的内容,以及模板解析器自己作为参数调用一个python函数。 这个函数负责返回一个和当前模板标签内容相对应的节点...

python 实时遍历日志文件

open 遍历一个大日志文件 使用 readlines() 还是 readline() ? 总体上 readlines() 不慢于python 一次次调用 readline(...

Python中三元表达式的几种写法介绍

要介绍Python的三元表达式,可以先看看其他编程语言比如C,JAVA中应用: public class java { public static void main(String...

使用Pytorch来拟合函数方式

其实各大深度学习框架背后的原理都可以理解为拟合一个参数数量特别庞大的函数,所以各框架都能用来拟合任意函数,Pytorch也能。 在这篇博客中,就以拟合y = ax + b为例(a和b为需...

对python中的高效迭代器函数详解

对python中的高效迭代器函数详解

python中内置的库中有个itertools,可以满足我们在编程中绝大多数需要迭代的场合,当然也可以自己造轮子,但是有现成的好用的轮子不妨也学习一下,看哪个用的顺手~ 首先还是要先im...