Django 响应数据response的返回源码详解


Posted in Python onAugust 06, 2019

响应数据的返回

在 WSGIHandler.__call__(self, environ, start_response) 方法调用了 WSGIHandler.get_response() 方法, 由此得到响应数据对象 response. 如今所要做的, 便是将其返回给客户端. 在 Django 源码小剖: 初探 WSGI 中, 简要的概括了请求到来时 django 自带服务器的执行关系, 摘抄如下:

  • make_server() 中 WSGIServer 类已经作为服务器类, 负责接收请求, 调用 application 的处理, 返回相应;
  • WSGIRequestHandler 作为请求处理类, 并已经配置在 WSGIServer 中;
  • 接着还设置了 WSGIServer.application 属性(set_app(app));
  • 返回 server 实例.
  • 接着打开浏览器, 即发起请求. 服务器实例 WSGIServer httpd 调用自身 handle_request() 函数处理请求. handle_request() 的工作流程如下:请求-->WSGIServer 收到-->调用 WSGIServer.handle_request()-->调用 _handle_request_noblock()-->调用 process_request()-->调用 finish_request()-->finish_request() 中实例化 WSGIRequestHandler-->实例化过程中会调用 handle()-->handle() 中实例化 ServerHandler-->调用 ServerHandler.run()-->run() 调用 application() 这才是真正的逻辑.-->run() 中在调用 ServerHandler.finish_response() 返回数据-->回到 process_request() 中调用 WSGIServer.shutdown_request() 关闭请求(其实什么也没做)

事实上, WSGIServer 并没有负责将响应数据返回给客户端, 它将客户端的信息(如最重要的客户端 socket 套接字)交接给了 WSGIRequestHandler, WSGIRequestHandler 又将客户端的信息交接给了 ServerHandler, 所以 ServerHandler 产生响应数据对象后, 会直接返回给客户端.

代码剖析

从「调用 ServerHandler.run()-->run() 调用 application() 这才是真正的逻辑.-->run() 中在调用 ServerHandler.finish_response() 返回数据」开始说起, 下面是主要的代码解说:

# 下面的函数都在 ServerHandler 的继承链上方法, 有些方法父类只定义了空方法, 具体逻辑交由子类实现. 有关继承链请参看: http://daoluan.net/blog/decode-django-wsgi/
def run(self, application):
 """Invoke the application"""
 try:
  self.setup_environ()
  # application 在 django 中就是 WSGIHandler 类, 他实现了 __call__ 方法, 所以行为和函数一样.
  self.result = application(self.environ, self.start_response)
  self.finish_response()
 except:
  # handle error
 
def finish_response(self):
 try:
  if not self.result_is_file() or not self.sendfile():
   for data in self.result:
    # 向套接字写数据, 将数据返回给客户端
    self.write(data)
   self.finish_content()
 finally:
  self.close()
 
def write(self, data):
 """'write()' callable as specified by PEP 333""" 
 # 必须是都是字符
 assert type(data) is StringType,"write() argument must be string" 
 if not self.status:
  raise AssertionError("write() before start_response()") 
 # 需要先发送 HTTP 头
 elif not self.headers_sent:
  # Before the first output, send the stored headers
  self.bytes_sent = len(data) # make sure we know content-length
  self.send_headers()
 # 再发送实体
 else:
  self.bytes_sent += len(data)
 
 # XXX check Content-Length and truncate if too many bytes written?
 self._write(data)
 self._flush()
 
def write(self, data):
 """'write()' callable as specified by PEP 3333"""
 
 assert isinstance(data, bytes), "write() argument must be bytestring"
 
 # 必须先调用 self.start_response() 设置状态码
 if not self.status:
  raise AssertionError("write() before start_response()")
 
 # 需要先发送 HTTP 头
 elif not self.headers_sent:
  # Before the first output, send the stored headers
  self.bytes_sent = len(data) # make sure we know content-length
  self.send_headers()
 # 再发送实体
 else:
  self.bytes_sent += len(data)
 
 # XXX check Content-Length and truncate if too many bytes written? 是否需要分段发送过大的数据?
 
 # If data is too large, socket will choke, 窒息死掉 so write chunks no larger
 # than 32MB at a time.
 
 # 分片发送
 length = len(data)
 if length > 33554432:
  offset = 0
  while offset < length:
   chunk_size = min(33554432, length)
   self._write(data[offset:offset+chunk_size])
   self._flush()
   offset += chunk_size
 else:
  self._write(data)
  self._flush()
 
def _write(self,data):
 # 如果是第一次调用, 则调用 stdout.write(), 理解为一个套接字对象
 self.stdout.write(data) 
 # 第二次调用就是直接调用 stdout.write() 了
 self._write = self.stdout.write

接下来的事情, 就是回到 WSGIServer 关闭套接字, 清理现场, web 应用程序由此结束; 但服务器依旧在监听(WSGIServer 用 select 实现)是否有新的请求, 不展开了.

阶段性的总结

请求到来至数据相应的流程已经走了一遍, 包括 django 内部服务器是如何运作的, 请求到来是如何工作的, 响应数据对象是如何产生的, url 是如何调度的, views.py 中定义的方法是何时调用的, 响应数据是如何返回的...另外还提出了一个更好的 url 调度策略, 如果你有更好的方法, 不忘与大家分享.

我已经在 github 备份了 Django 源码的注释: Decode-Django, 有兴趣的童鞋 fork 吧.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
解析Python中的二进制位运算符
May 13 Python
JSON Web Tokens的实现原理
Apr 02 Python
python字符串string的内置方法实例详解
May 14 Python
查看Django和flask版本的方法
May 14 Python
Python识别快递条形码及Tesseract-OCR使用详解
Jul 15 Python
Django logging配置及使用详解
Jul 23 Python
python获取array中指定元素的示例
Nov 26 Python
基于python实现数组格式参数加密计算
Apr 21 Python
python filecmp.dircmp实现递归比对两个目录的方法
May 22 Python
python 代码实现k-means聚类分析的思路(不使用现成聚类库)
Jun 01 Python
django跳转页面传参的实现
Sep 17 Python
Python实现http接口自动化测试的示例代码
Oct 09 Python
详解Python Matplotlib解决绘图X轴值不按数组排序问题
Aug 05 #Python
Django中提供的6种缓存方式详解
Aug 05 #Python
python修改字典键(key)的方法
Aug 05 #Python
python中使用while循环的实例
Aug 05 #Python
Python3 列表,数组,矩阵的相互转换的方法示例
Aug 05 #Python
Python中print函数简单使用总结
Aug 05 #Python
Numpy数组array和矩阵matrix转换方法
Aug 05 #Python
You might like
常见PHP数据库解决方案分析介绍
2015/09/24 PHP
使用PHP如何实现高效安全的ftp服务器(二)
2015/12/30 PHP
JavaScript建立一个语法高亮输入框实现思路
2013/02/26 Javascript
JavaScript自执行闭包的小例子
2013/06/29 Javascript
JavaScript中5种调用函数的方法
2015/03/12 Javascript
js实现的动画导航菜单效果代码
2015/09/10 Javascript
js判断输入字符串是否为空、空格、null的方法总结
2016/06/14 Javascript
js动态生成form 并用ajax方式提交的实现方法
2016/09/09 Javascript
JS简单实现数组去重的方法示例
2017/03/27 Javascript
vue-music关于Player播放器组件详解
2017/11/28 Javascript
layui实现三级联动效果
2019/07/26 Javascript
基于vue中的scoped坑点解说
2020/09/04 Javascript
python连接mysql并提交mysql事务示例
2014/03/05 Python
Python实现提取文章摘要的方法
2015/04/21 Python
在Python中使用PIL模块对图片进行高斯模糊处理的教程
2015/05/05 Python
Python中字典创建、遍历、添加等实用操作技巧合集
2015/06/02 Python
Python正规则表达式学习指南
2016/08/02 Python
python中json格式数据输出的简单实现方法
2016/10/31 Python
python爬取网页转换为PDF文件
2018/06/07 Python
Python利用scapy实现ARP欺骗的方法
2019/07/23 Python
pytorch在fintune时将sequential中的层输出方法,以vgg为例
2019/08/20 Python
pytorch 图像中的数据预处理和批标准化实例
2020/01/15 Python
Python调用ffmpeg开源视频处理库,批量处理视频
2020/11/16 Python
浅谈Selenium+Webdriver 常用的元素定位方式
2021/01/13 Python
安全生产先进个人材料
2014/02/06 职场文书
保密承诺书范文
2014/03/27 职场文书
2015年乡镇纪检工作总结
2015/04/22 职场文书
员工年度工作总结2015
2015/05/18 职场文书
离婚撤诉申请书范本
2015/05/18 职场文书
工程款催款函
2015/06/24 职场文书
中学后勤工作总结2015
2015/07/22 职场文书
商场广播稿范文
2015/08/19 职场文书
《打电话》教学反思
2016/02/22 职场文书
2016年小学推普宣传周活动总结
2016/04/06 职场文书
Win11如何查看显卡型号 Win11查看显卡型号的方法
2022/08/14 数码科技
clear 万能清除浮动(clearfix:after)
2023/05/21 HTML / CSS