zoukankan      html  css  js  c++  java
  • django中的FBV和CBV

     

     

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

    一、FBV

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

    看代码:

    urls.py

    1
    2
    3
    4
    5
    6
    7
    8
    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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!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的使用。

    二、CBV

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

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

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

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

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    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‘)

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

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

  • 相关阅读:
    【二分图】HEOI2012 朋友圈
    【转载】动态规划—各种 DP 优化
    【默哀】京阿尼纵火案一周年
    【暑假集训】HZOI2019 Luogu P1006 传纸条 二三四维解法
    【暑假集训】HZOI2019 水站 多种解法
    最小二乘法求线性回归方程
    51Nod 最大M子段和系列 V1 V2 V3
    【博弈论】51Nod 1534 棋子游戏
    【最短路】CF 938D Buy a Ticket
    51nod1524 最大子段和V2
  • 原文地址:https://www.cnblogs.com/xc1234/p/9152075.html
Copyright © 2011-2022 走看看