django中的FBV和CBV??

django中请求处理方式有2种:FBV 和 CBV

一、FBV

FBV(function base views) 就是在视图里使用函数处理请求。

看代码:

urls.py

1 from django.conf.urls import url, include
2 # from django.contrib import admin
3 from mytest import views
4  
5 urlpatterns = [
6     # url(r‘^admin/‘, admin.site.urls),
7     url(r‘^index/‘, views.index),
8 ]

views.py

1 from django.shortcuts import render
2  
3  
4 def index(req):
5     if req.method == ‘POST‘:
6         print(‘method is :‘ + req.method)
7     elif req.method == ‘GET‘:
8         print(‘method is :‘ + req.method)
9     return render(req, ‘index.html‘)

注意此处定义的是函数【def index(req):】

index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>index</title>
 6 </head>
 7 <body>
 8     <form action="" method="post">
 9         <input type="text" name="A" />
10         <input type="submit" name="b" value="提交" />
11     </form>
12 </body>
13 </html>

上面就是FBV的使用。

二、CBV

CBV(class base views) 就是在视图里使用类处理请求。

将上述代码中的urls.py 修改为如下:

1 from mytest import views
2  
3 urlpatterns = [
4     # url(r‘^index/‘, views.index),
5     url(r‘^index/‘, views.Index.as_view()),
6 ]

注:url(r‘^index/‘, views.Index.as_view()),  是固定用法。

将上述代码中的views.py 修改为如下:

 1 from django.views import View
 2  
 3 class Index(View):
 4     def get(self, req):
 5         print(‘method is :‘ + req.method)
 6         return render(req, ‘index.html‘)
 7  
 8     def post(self, req):
 9         print(‘method is :‘ + req.method)
10         return render(req, ‘index.html‘)

注:类要继承 View ,类中函数名必须小写。

两种方式没有优劣,都可以使用。

原文地址:https://www.cnblogs.com/lmh001/p/9756032.html