Django——CBV源码解析

Django——CBV源码解析

以下是views模块调用as_view()方法的代码示例

# urls.py
from django.contrib import admin
from django.urls import path
import app.viewsurlpatterns = [path('admin/', admin.site.urls),path('app/', app.views.task.as_view()),
]
# views.py
class task(View):# 根据id获取def get(self, request, u_id):response = {'code': '200', 'msg': "查询成功"}return JsonResponse(json.dumps(response), safe=False)

该功能实现的是当有get请求发送到app这个接口时会返回一个response字典

首先引入问题:为什么浏览器向后端发送get请求时会被该get方法精准接受?

其实是因为在注册url时app.views调用的as_view()方法帮我们做好了大部分规划

Ctrl+左键进入as_view()源码

class View:http_method_names = ["get","post","put","patch","delete","head","options","trace",]def __init__(self, **kwargs):for key, value in kwargs.items():setattr(self, key, value)@classonlymethoddef as_view(cls, **initkwargs):"""Main entry point for a request-response process."""for key in initkwargs:if key in cls.http_method_names:raise TypeError("The method name %s is not accepted as a keyword argument ""to %s()." % (key, cls.__name__))if not hasattr(cls, key):raise TypeError("%s() received an invalid keyword %r. as_view ""only accepts arguments that are already ""attributes of the class." % (cls.__name__, key))def view(request, *args, **kwargs):self = cls(**initkwargs)self.setup(request, *args, **kwargs)if not hasattr(self, "request"):raise AttributeError("%s instance has no 'request' attribute. Did you override ""setup() and forget to call super()?" % cls.__name__)return self.dispatch(request, *args, **kwargs)view.view_class = clsview.view_initkwargs = initkwargs# __name__ and __qualname__ are intentionally left unchanged as# view_class should be used to robustly determine the name of the view# instead.view.__doc__ = cls.__doc__view.__module__ = cls.__module__view.__annotations__ = cls.dispatch.__annotations__# Copy possible attributes set by decorators, e.g. @csrf_exempt, from# the dispatch method.view.__dict__.update(cls.dispatch.__dict__)# Mark the callback if the view class is async.if cls.view_is_async:markcoroutinefunction(view)return viewdef dispatch(self, request, *args, **kwargs):# Try to dispatch to the right method; if a method doesn't exist,# defer to the error handler. Also defer to the error handler if the# request method isn't on the approved list.if request.method.lower() in self.http_method_names:handler = getattr(self, request.method.lower(), self.http_method_not_allowed)else:handler = self.http_method_not_allowedreturn handler(request, *args, **kwargs)def http_method_not_allowed(self, request, *args, **kwargs):logger.warning("Method Not Allowed (%s): %s",request.method,request.path,extra={"status_code": 405, "request": request},)response = HttpResponseNotAllowed(self._allowed_methods())if self.view_is_async:async def func():return responsereturn func()else:return response
  • @classonlymethod表示只能用类调用此方法,这也是为什么我们只能用as_views()而不是as_views
  • 这个时候我们来到了task(View)继承的View类下的as_view()方法
  • 中间的步骤先不管 直接看return view
def view(request, *args, **kwargs):self = cls(**initkwargs)self.setup(request, *args, **kwargs)if not hasattr(self, "request"):raise AttributeError("%s instance has no 'request' attribute. Did you override ""setup() and forget to call super()?" % cls.__name__)return self.dispatch(request, *args, **kwargs)
  • 这个时候可以看出其实我们就是在调用父类的view方法
  • 这里的request参数就是我们的浏览器接受的request请求,如果没填request则会弹出一个error
  • 重点是最后调用了实例中的dispatch方法
  • 既然我们的task类调用了dispatch方法那么就应该在task类下搜寻这个方法,但是很明显我们没有写过这方法,因此又回到父类View中的dispatch方法(这俩方法挨得很近,往下翻翻就找到了)
def dispatch(self, request, *args, **kwargs):# Try to dispatch to the right method; if a method doesn't exist,# defer to the error handler. Also defer to the error handler if the# request method isn't on the approved list.if request.method.lower() in self.http_method_names:handler = getattr(self, request.method.lower(), self.http_method_not_allowed)else:handler = self.http_method_not_allowedreturn handler(request, *args, **kwargs)
  • if request.method.lower() in self.http_method_names:当我们的request请求类型存在于http_method_names
  • 那么先看看这个http_method_names是什么东西
http_method_names = ["get","post","put","patch","delete","head","options","trace",
]
  • 其实就是个定义好的字符串列表
  • 再接着看dispatch
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  • 其实就是从我们task实例中获取相应的HTTP请求方法,如果不存在就用它默认的
  • 最后返回handler,再解释一下gatter的用法
class Test(object):x = 1a = Test()
print(getattr(a, 'x'))  # 获取属性 x 值
# 结果:1
print(getattr(a, 'y', 'None'))  # 获取属性 y 值不存在,但设置了默认值
# 结果:None
print(a.x)  # 效果等同于上面
# 结果:1
  • 回到我们最初的问题为什么浏览器向后端发送get请求时会被该get方法精准接受?
  • 走到这里基本可以得出结论了,说白了就是如果我有get就走我类下的get方法,没有就走它默认的

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/818005.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Day55 动态规划 part15

Day55 动态规划 part15 392.判断子序列 我的思路: 自己还是只能想到双指针法 解答: class Solution {public boolean isSubsequence(String s, String t) {if(s.length() 0) {return true;}if(s.length() > t.length() || t.length() 0) {return false;}ch…

性能再升级!UNet+注意力机制,新SOTA分割准确率高达99%

UNet结合注意力机制能够有效提升图像分割任务的性能。 具体来说,通过将注意力模块集成到UNet的架构中,动态地重新分配网络的焦点,让其更集中在图像中对于分割任务关键的部分。这样UNet可以更有效地利用其跳跃连接特性,以精细的局…

VMware安装Linux虚拟机(rocky9)

软件准备: VMware虚拟机ISO系统镜像文件 选择创建虚拟机→典型→下一步→点击稍后安装操作系统 选择Linux系统和对应版本 输入虚拟机名称和选择保存位置 设置磁盘大小 根据需要自定义硬件配置→完成 然后点击编辑虚拟机设置→CD/DVD→选择ISO镜像 然后开启虚拟机→…

动态规划|343.整数拆分

力扣题目链接 class Solution { public:int integerBreak(int n) {vector<int> dp(n 1);dp[2] 1;for (int i 3; i < n ; i) {for (int j 1; j < i / 2; j) {dp[i] max(dp[i], max((i - j) * j, dp[i - j] * j));}}return dp[n];} }; 思路 看到这道题目&…

【GD32】 2.39 FR1002人脸识别模块

2.39 FR1002人脸识别模块 FR1002人脸识别模组解决方案以高性能应用处理器为硬件平台&#xff0c;配合双目传感器进行活体检测&#xff0c;具有启动速度快、金融级的识别能力、超低使用功耗等特点。凭借超低功耗、强大的运算速度&#xff0c;在多种应用领域中&#xff0c;为各行…

关于《CS创世 SD NAND》的技术学习分享

最近发现一个好玩的东西《CS创世 SD NAND》&#xff0c;带大家一起体验一下。 本文引用了部分厂家产品资料及图像&#xff0c;如有侵权&#xff0c;请及时联系我删除&#xff0c;谢谢。 《CS创世 SD NAND》官方网站&#xff1a;http://www.longsto.com/ 什么是CS创世 SD NAND呢…

0基础刷图论最短路 1(从ATcoder 0分到1800分)

ATC最短路1 &#xff08;本文难度rated 0~ 1000&#xff09; 题目来源&#xff1a;Atcoder 题目收集&#xff1a; https://atcoder-tags.herokuapp.com/tags/Graph/Shortest-Path &#xff08;里面按tag分类好了Atcoder的所有题目&#xff0c;类似cf&#xff09; &#xff08;…

Linux 关闭交换分区(swap)

安装Doris、ElasticSearch等服务的时候&#xff0c;Linux交换分区会给这些服务带来很严重的性能问题&#xff0c;需要在安装之前禁用交换分区。 1 查看交换分区信息 首先&#xff0c;使用 swapon --show 或 cat /proc/swaps 命令来查看当前的交换分区状态。它会列出所有当前启…

【300套】基于Springboot+Vue的Java实战开发项目(附源码+演示视频+LW)

大家好&#xff01;我是程序员一帆&#xff0c;感谢您阅读本文&#xff0c;欢迎一键三连哦。 &#x1f9e1;今天给大家分享300的Java毕业设计&#xff0c;基于Springbootvue框架&#xff0c;这些项目都经过精心挑选&#xff0c;涵盖了不同的实战主题和用例&#xff0c;可做毕业…

【vue】用vite创建vue项目

前置要求 要有Node.js 1. 用vite创建vue项目 在cmd中&#xff0c;进入一个文件夹 在文件资源管理器上面的文件目录中&#xff0c;输入cmd&#xff0c;回车在cmd中通过cd命令进入对应文件夹 创建项目 npm create vitelatest # 创建项目创建项目过程中的一些选项 Ok to pro…

Fake-SMS恶意软件混淆分析——低代码的时代来了

写在前面的话 在安全社区中&#xff0c;只要聊到开源代码使用方面的话题&#xff0c;就肯定会聊到安全问题。虽然使用开源代码通常会被认为是安全的&#xff0c;但我们需要清楚的是&#xff0c;与非FOSS&#xff08;自由与开源软件&#xff09;解决方案相比&#xff0c;开源软…

Hive on spark源码编译与调优

文章目录 一、编译环境准备1、hadoop和hive安装2、编译环境搭建3、Hive on Spark配置 二、Hive相关问题1、Hadoop和Hive的兼容性问题1.1 问题描述1.2 解决思路1.3 修改并编译Hive源码 2、Hive插入数据StatsTask失败问题3.1 问题描述3.2 解决思路 3、Hive和Spark兼容性问题3.1 问…

【Android surface 】二:源码分析App的surface创建过程

文章目录 画布surfaceViewRoot的创建&setView分析setViewrequestLayoutViewRoot和WMS的关系 activity的UI绘制draw surfacejni层分析Surface无参构造SurfaceSessionSurfaceSession_init surface的有参构造Surface_copyFromSurface_writeToParcelSurface_readFromParcel 总结…

【Hive上篇: 一篇文章带你使用Hive!深入了解Hive!学会Hive!】

前言&#xff1a; &#x1f49e;&#x1f49e;大家好&#xff0c;我是书生♡&#xff0c;本篇文章主要分享的是大数据开发中hive的相关技术&#xff0c;什么是Hive&#xff1f;怎么使用Hive&#xff1f;怎么安装部署&#xff1f;希望大家看完这篇文章会有所帮助。也希望大家能够…

运筹优化库Qaekwy入门——以指派问题为例

文章目录 1. 什么是 Qaekwy?2. 安装方法(Windows)3. 指派问题3.1 描述问题3.2 建立问题模型3.3 模型求解1. 什么是 Qaekwy? 在 2023 年 9 月 Github 上开源了一个新的优化求解器 Qaekwy,根据官方对 Qaekey 的介绍,该求解器严格来说是一个 Python 客户端,通过 Python 接…

Depth maps转点云

前言 本文主要记录一下如何可视化相机位姿&#xff0c;如何用Blender得到的深度图反投影到3D空间&#xff0c;得到相应的点云。 Refernce https://github.com/colmap/colmap/issues/1106 https://github.com/IntelRealSense/librealsense/issues/12090 https://medium.com/yod…

【详细讲解下Photoshop】

&#x1f3a5;博主&#xff1a;程序员不想YY啊 &#x1f4ab;CSDN优质创作者&#xff0c;CSDN实力新星&#xff0c;CSDN博客专家 &#x1f917;点赞&#x1f388;收藏⭐再看&#x1f4ab;养成习惯 ✨希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出…

大模型推理过程

在人工智能领域&#xff0c;尤其是在机器学习和深度学习中&#xff0c;“推理”&#xff08;Inference&#xff09;是指使用训练好的模型来进行预测或决策的过程。在模型被训练以学习数据的特征和模式之后&#xff0c;推理就是将实际的数据输入模型&#xff0c;以获得输出结果的…

鸿蒙 Failed :entry:default@CompileResource...

Failed :entry:defaultCompileResource... media 文件夹下有文件夹或者图片名称包含中文字符 rawfile 文件夹下文件名称、图片名称不能包含中文字符

地理空间分析中的深度学习应用

深度学习与地理信息系统 (GIS) 的结合彻底改变了地理空间分析和遥感的格局。这种结合将遥感和地理空间分析领域带到了全球研究人员和科学家的前沿。 深度学习是机器学习的一个复杂子集&#xff08;更多关于机器学习的内容&#xff0c;请参阅我的其他文章&#xff09;&#xff0…