程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(2)

django中的FBV和CBV

发布于2019-08-22 15:41     阅读(1242)     评论(0)     点赞(3)     收藏(2)


                  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 ,类中函数名必须小写。

 

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

django中的FBV和CBV

标签:base   text   onf   div   spa   2种   inpu   site   .py   

原文:http://www.cnblogs.com/wumingxiaoyao/p/6513981.html



所属网站分类: 技术文章 > 博客

作者:滴水

链接:https://www.pythonheidong.com/blog/article/52521/97016f7024be39099ba7/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

3 0
收藏该文
已收藏

评论内容:(最多支持255个字符)