Django之FBV和CBV

一、FBV与CBV

在我们日常学习Django中,都是用的FBV(function base views)方式,就是在视图中用函数处理各种请求。而CBV(class base view)则是通过类来处理请求。

Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了Class-Based-View。可以让我们用类写View。

这样做的优点主要下面两种:

  1. 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
  2. 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性;

二、示例

1、urls.py

python 复制代码
from django.urls import path
from app01 import views

urlpatterns = [
    # path('admin/', admin.site.urls),

    #FBV路由写法,基于函数
    path('auth/', views.auth),

    #CBV写法,基于类的路由写法
    path('user/',views.UserView.as_view()),

2、views.py

python 复制代码
from django.http import JsonResponse
from django.views import View

#FBV的写法
def auth(request):
    if request.method == "GET":
        return JsonResponse({"status":True,"message":"GET"})
    elif request.method == "POST":
        return JsonResponse({"status": True, "message": "POST"})
    return JsonResponse({"status":True,"message":"..."})

#CBV写法
class UserView(View):
    def get(self,request):
        return JsonResponse({"status":True,"message":"get"})

    def post(self,request):
        return JsonResponse({"status":True,"message":"post"})

    def put(self,request):
        return JsonResponse({"status": True, "message": "put"})

    def delete(self,request):
        return JsonResponse({"status": True, "message": "delete"})
相关推荐
久绊A1 小时前
Python 基本语法的详细解释
开发语言·windows·python
Hylan_J5 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶5 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
闲猫5 小时前
go orm GORM
开发语言·后端·golang
丁卯4045 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
失败尽常态5238 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447748 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农8 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿8 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Leuanghing8 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode