Django如何定义视图函数?FBV-CBV的使用场景

目录

[1. 前言](#1. 前言)

[2. FBV与CBV](#2. FBV与CBV)

[2.1 FBV](#2.1 FBV)

[2.2 CBV](#2.2 CBV)

[2.3 两种区别](#2.3 两种区别)

[3. request参数](#3. request参数)

[4. 返回值](#4. 返回值)

[5. 结尾](#5. 结尾)


1. 前言

在Django中,我们通过浏览器URL发送了请求,请求通过路由层,最后匹配到相应的视图函数

在视图函数中,也分两种编写形式:FBV、CBV

接下来,我们来看看CBV和FBV两种范式

2. FBV与CBV

2.1 FBV

所谓FBV就是function based views ,函数式编写视图,也就是通过函数的形式,来编写视图:

python 复制代码
def test(request):
    print(request.resolver_match)
    return HttpResponse('code')

这就是最简单的FBV编写视图的形式。

但是我们请求是分为很多种的,我们需要额外进行判断:

python 复制代码
def test(request):
    if request.method == 'GET':
        print(request.resolver_match)
        return HttpResponse('get')
    else:
        return HttpResponse('这是post')

2.2 CBV

所谓CBV就是clss based views ,类编写视图,也就是通过类的形式,来编写视图:

python 复制代码
class User(View):
    def get(self , request):
        print('hello')
        return HttpResponse('我是get')

    def post(self , request):
        return HttpResponse('我是post')

在CBV中,一种函数代表一种请求方式

2.3 两种区别

  • 定义路由的形式不同

FBV:

复制代码
path('test/', views.test)

CBV:

复制代码
path('user/' , views.User.as_view())
  • 应用范围一般不同

FBV:

一般用于前后端不分离

CBV:

一般用于前后端分离(小程序API ,DRF)

3. request参数

request封装了HTTP请求对象,本质上是一个WSGIRequest对象,源码如下:

我们大致可以看看request里面都有什么,这肯定少不了源码啦(这个时候,研究源码的好处就来咯)

python 复制代码
    def __init__(self, environ):
        script_name = get_script_name(environ)
        # If PATH_INFO is empty (e.g. accessing the SCRIPT_NAME URL without a
        # trailing slash), operate as if '/' was requested.
        path_info = get_path_info(environ) or "/"
        self.environ = environ
        self.path_info = path_info
        # be careful to only replace the first slash in the path because of
        # http://test/something and http://test//something being different as
        # stated in RFC 3986.
        self.path = "%s/%s" % (script_name.rstrip("/"), path_info.replace("/", "", 1))
        self.META = environ
        self.META["PATH_INFO"] = path_info
        self.META["SCRIPT_NAME"] = script_name
        self.method = environ["REQUEST_METHOD"].upper()
        # Set content_type, content_params, and encoding.
        self._set_content_type_params(environ)
        try:
            content_length = int(environ.get("CONTENT_LENGTH"))
        except (ValueError, TypeError):
            content_length = 0
        self._stream = LimitedStream(self.environ["wsgi.input"], content_length)
        self._read_started = False
        self.resolver_match = None

我们大概可以梳理一下:

当然,下面还有很多方法可以使用,常用的就这几个:

python 复制代码
request.method    # 请求方法
request.GET        # get请求参数,也就是url的?后面的
reqeust.POST      # post请求参数
request.FILES     # 文件参数
request.path_info   # 路径
request.body   # 原始请求数据

4. 返回值

python 复制代码
from Django.http import JsonResponse
from django.shortcuts import render, HttpResponse,redirect
  • HttpResponse:构建响应体和响应头,返回字符串
  • JsonResponse:json格式

一般JsonResponse返回的数据中文是乱码的 , 这个时候就要加上后面的参数.

python 复制代码
中文显示:
JsonResponse({"吊毛": 1}, json_dumps_params={'ensure_ascii': False})
  • render:返回html页面
  • redirect:重定向 301/ 302
python 复制代码
301和302
301:永久重定向,相当于直接替换掉,一般用于域名跳转
302:临时重定向,相当于保留原地址,一般用作临时的跳转

5. 结尾

Django业务开发离不开视图层,熟练掌握视图层,能让我们更好的开发业务需求。

我们经常都会用到requets封装的参数,例如获取请求方法、请求体等

最后就是返回值问题,HttpResponse一般用于返回字符串内容,而JsonResponse一般返回json数据等等,采用合适的返回值能让业务走的更流通。

相关推荐
陈苏同学15 分钟前
4. 将pycharm本地项目同步到(Linux)服务器上——深度学习·科研实践·从0到1
linux·服务器·ide·人工智能·python·深度学习·pycharm
唐家小妹18 分钟前
介绍一款开源的 Modern GUI PySide6 / PyQt6的使用
python·pyqt
杨哥带你写代码30 分钟前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端
羊小猪~~1 小时前
深度学习项目----用LSTM模型预测股价(包含LSTM网络简介,代码数据均可下载)
pytorch·python·rnn·深度学习·机器学习·数据分析·lstm
A尘埃1 小时前
SpringBoot的数据访问
java·spring boot·后端
yang-23071 小时前
端口冲突的解决方案以及SpringBoot自动检测可用端口demo
java·spring boot·后端
Marst Code1 小时前
(Django)初步使用
后端·python·django
代码之光_19801 小时前
SpringBoot校园资料分享平台:设计与实现
java·spring boot·后端
向上的车轮1 小时前
Django学习笔记二:数据库操作详解
数据库·django
985小水博一枚呀1 小时前
【对于Python爬虫的理解】数据挖掘、信息聚合、价格监控、新闻爬取等,附代码。
爬虫·python·深度学习·数据挖掘