1. 程式人生 > >Django請求處理的兩種方式:FBV 和 CBV

Django請求處理的兩種方式:FBV 和 CBV

django中請求處理方式有2種:FBV 和 CBV

一、FBV

FBV(function base views) 就是在視圖裡使用函式處理請求。

看程式碼:

urls.py

from django.conf.urls import url, include
from mytest import views 


urlpatterns = [ 
    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>

二、CBV

CBV(class base views) 就是在視圖裡使用類處理請求。

將上述程式碼中的urls.py 修改為如下:

from mytest import views

urlpatterns = [
    url(r‘^index/‘, views.Index.as_view()),
]

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

將上述程式碼中的views.py 修改為如下:

from django.views import View


class Index(View):
    def get(self, req):
        print(‘method is :‘ + req.method)
        return render(req, ‘index.html‘)

    def post(self, req):
        print(‘method is :‘ + req.method)
        return render(req, ‘index.html‘)

 

參考文章

https://blog.csdn.net/qq471011042/article/details/79344526

https://blog.csdn.net/qq471011042/article/details/79347062