Django应用程序入口WSGIHandler源码解析


Posted in Python onAugust 05, 2019

前言

WSGI 有三个部分, 分别为服务器(server), 应用程序(application) 和中间件(middleware). 已经知道, 服务器方面会调用应用程序来处理请求, 在应用程序中有真正的处理逻辑, 在这里面几乎可以做任何事情, 其中的中间件就会在里面展开.

Django 中的应用程序

任何的 WSGI 应用程序, 都必须是一个 start_response(status, response_headers, exc_info=None) 形式的函数或者定义了 __call__ 的类. 而 django.core.handlers 就用后一种方式实现了应用程序: WSGIHandler. 在这之前, Django 是如何指定自己的 application 的, 在一个具体的 Django 项目中, 它的方式如下:

在 mysite.settings.py 中能找到如下设置:

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'tomato.wsgi.application'

如你所见, WSGI_APPLICATION 就指定了应用程序. 而按图索骥下去, 找到项目中的 wsgi.py, 已经除去了所有的注释:

import os 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tomato.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

因此, WSGI_APPLICATION 所指定的即为 wsgi.py 中的全局变量 application. 故伎重演, 继续找下去. 在 django.core 模块中的 wsgi.py 中找到 get_wsgi_application() 函数的实现:

from django.core.handlers.wsgi import WSGIHandler
def get_wsgi_application():
  """
  The public interface to Django's WSGI support. Should return a WSGI
  callable. 
  Allows us to avoid making django.core.handlers.WSGIHandler public API, in
  case the internal WSGI implementation changes or moves in the future.
 
  """
  """
  # 继承, 但只实现了 __call__ 方法, 方便使用
  class WSGIHandler(base.BaseHandler):
  """
  return WSGIHandler()

在 get_wsgi_application() 中实例化了 WSGIHandler, 并无其他操作.

WSGIHandler

紧接着在 django.core.handler 的 base.py 中找到 WSGIHandler 的实现.

# 继承, 但只实现了 __call__ 方法, 方便使用
class WSGIHandler(base.BaseHandler):
  initLock = Lock() 
  # 关于此, 日后展开, 可以将其视为一个代表 http 请求的类
  request_class = WSGIRequest 
  # WSGIHandler 也可以作为函数来调用
  def __call__(self, environ, start_response):
    # Set up middleware if needed. We couldn't do this earlier, because
    # settings weren't available. 
    # 这里的检测: 因为 self._request_middleware 是最后才设定的, 所以如果为空,
    # 很可能是因为 self.load_middleware() 没有调用成功.
    if self._request_middleware is None:
      with self.initLock:
        try:
          # Check that middleware is still uninitialised.
          if self._request_middleware is None:
            因为 load_middleware() 可能没有调用, 调用一次.
            self.load_middleware()
        except:
          # Unload whatever middleware we got
          self._request_middleware = None
          raise 
    set_script_prefix(base.get_script_name(environ))
    signls.request_started.send(sender=self.__class__) # __class__ 代表自己的类 
    try:
      # 实例化 request_class = WSGIRequest, 将在日后文章中展开, 可以将其视为一个代表 http 请求的类
      request = self.request_class(environ)
 
    except UnicodeDecodeError:
      logger.warning('Bad Request (UnicodeDecodeError)',
        exc_info=sys.exc_info(),
        extra={
          'status_code': 400,
        }
      )
      response = http.HttpResponseBadRequest()
    else:
      # 调用 self.get_response(), 将会返回一个相应对象 response<br>      ############# 关键的操作, self.response() 可以获取响应数据.     
      response = self.get_response(request)
 
    # 将 self 挂钩到 response 对象
    response._handler_class = self.__class__ 
    try:
      status_text = STATUS_CODE_TEXT[response.status_code]
    except KeyError:
      status_text = 'UNKNOWN STATUS CODE'
     # 状态码
    status = '%s %s' % (response.status_code, status_text) 
    response_headers = [(str(k), str(v)) for k, v in response.items()] 
    # 对于每个一个 cookie, 都在 header 中设置: Set-cookie xxx=yyy
    for c in response.cookies.values():
      response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
 
    # start_response() 操作已经在上节中介绍了
    start_response(force_str(status), response_headers) 
    # 成功返回相应对象
    return response

WSGIHandler 类只实现了 def __call__(self, environ, start_response), 使它本身能够成为 WSGI 中的应用程序, 并且实现 __call__ 能让类的行为跟函数一样, 详见 python __call__ 方法.

def __call__(self, environ, start_response) 方法中调用了 WSGIHandler.get_response() 方法以获取响应数据对象 response. 从 WSGIHandler 的实现来看, 它并不是最为底层的: WSGIHandler 继承自 base.BaseHandler, 在 django.core.handler 的 base.py 中可以找到: class BaseHandler(object):...

这一节服务器部分已经结束, 接下来的便是中间件和应用程序了, 相关内容会在下节的 BaseHandler 中展开. 我已经在 github 备份了 Django 源码的注释: Decode-Django, 有兴趣的童鞋 fork 吧.

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

Python 相关文章推荐
python通过get,post方式发送http请求和接收http响应的方法
May 26 Python
python实现的用于搜索文件并进行内容替换的类实例
Jun 28 Python
Python3 伪装浏览器的方法示例
Nov 23 Python
python3实现磁盘空间监控
Jun 21 Python
OPENCV去除小连通区域,去除孔洞的实例讲解
Jun 21 Python
Python遍历文件夹 处理json文件的方法
Jan 22 Python
Python基础知识点 初识Python.md
May 14 Python
详解Python list和numpy array的存储和读取方法
Nov 06 Python
Python测试线程应用程序过程解析
Dec 31 Python
Tensorflow 定义变量,函数,数值计算等名字的更新方式
Feb 10 Python
Python如何读写二进制数组数据
Aug 01 Python
 Python 中 logging 模块使用详情
Mar 03 Python
详解如何用TensorFlow训练和识别/分类自定义图片
Aug 05 #Python
详解如何从TensorFlow的mnist数据集导出手写体数字图片
Aug 05 #Python
Python获取时间范围内日期列表和周列表的函数
Aug 05 #Python
Django ORM 查询管理器源码解析
Aug 05 #Python
python实现车牌识别的示例代码
Aug 05 #Python
使用python实现滑动验证码功能
Aug 05 #Python
Django 源码WSGI剖析过程详解
Aug 05 #Python
You might like
php下用GD生成生成缩略图的两个选择和区别
2007/04/17 PHP
fleaphp crud操作之findByField函数的使用方法
2011/04/23 PHP
基于php伪静态的实现详细介绍
2013/04/28 PHP
解析php类的注册与自动加载
2013/07/05 PHP
php使用array_chunk函数将一个数组分割成多个数组
2018/12/05 PHP
详解laravel passport OAuth2.0的4种模式
2019/11/04 PHP
php多进程并发编程防止出现僵尸进程的方法分析
2020/02/28 PHP
基于jquery的无缝循环新闻列表插件
2011/03/07 Javascript
javascript中的startWith和endWith的几种实现方法
2013/05/07 Javascript
javascript实现获取cookie过期时间的变通方法
2014/08/14 Javascript
JS数组(Array)处理函数整理
2014/12/07 Javascript
JavaScript中检查对象property的存在性方法介绍
2014/12/30 Javascript
js通过iframe加载外部网页的实现代码
2015/04/05 Javascript
在JavaScript中call()与apply()区别
2016/01/22 Javascript
使用jQuery制作基础的Web图片轮播效果
2016/04/22 Javascript
jQuery的框架介绍
2016/05/11 Javascript
JavaScript对象数组排序实例方法浅析
2016/06/15 Javascript
深入理解JavaScript函数参数(推荐)
2016/07/26 Javascript
动态统计当前输入内容的字节、字符数的实例详解
2017/10/27 Javascript
nodejs(officegen)+vue(axios)在客户端导出word文档的方法
2018/07/31 NodeJs
vue+iview/elementUi实现城市多选
2019/03/28 Javascript
jQuery实现图片下载代码
2019/07/18 jQuery
Ant Design的可编辑Tree的实现操作
2020/10/31 Javascript
[04:09]2018年度DOTA2社区贡献奖-完美盛典
2018/12/16 DOTA
Python与Java间Socket通信实例代码
2017/03/06 Python
Python实现的KMeans聚类算法实例分析
2018/12/29 Python
python软件都是免费的吗
2020/06/18 Python
德国网上药房:Apotal
2017/04/04 全球购物
德国汽车零件和汽车配件网上商店:kfzteile24
2018/11/14 全球购物
德国珠宝和配件商店:Styleserver
2021/02/23 全球购物
地球物理学专业推荐信
2014/09/08 职场文书
违纪检讨书范文
2015/01/27 职场文书
高考学习决心书
2015/02/04 职场文书
开除员工通知
2015/04/22 职场文书
《攀登者》:“海拔8000米以上,你不能指望任何人”
2019/11/25 职场文书
Java 在线考试云平台的实现
2021/11/23 Java/Android