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

作者:捣乱小子 时间:2021-07-09 04:33:22 

前言

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 吧.

来源:https://www.cnblogs.com/daoluanxiaozi/p/3315838.html

标签:django,应用程序,入口,wsgi,handler
0
投稿

猜你喜欢

  • 常用照片尺寸

    2009-03-06 12:56:00
  • python返回数组的索引实例

    2023-11-01 04:48:17
  • 讨论闭包传入参数:window & undefined

    2010-05-19 12:55:00
  • 解读ASP.NET 5 & MVC6系列教程(2):初识项目

    2023-06-28 02:10:47
  • 基于php权限分配的实现代码

    2023-11-14 11:10:49
  • php中instanceof 与 is_a()区别分析

    2023-11-19 06:04:56
  • Python图像处理之使用OpenCV检测对象颜色

    2023-05-20 01:00:18
  • php输出文字乱码的解决方法

    2023-11-11 07:40:08
  • python读取word 中指定位置的表格及表格数据

    2021-04-10 02:42:21
  • python调用cmd命令行制作刷博器

    2023-07-26 15:18:35
  • python实现抖音点赞功能

    2023-08-13 04:06:50
  • 简析 IOS 程序图标的设计

    2011-04-28 09:39:00
  • Python基础之常用库常用方法整理

    2022-10-30 10:43:26
  • 解析:轻松掌握在 Mac OS X中安装MySQL

    2009-01-14 11:51:00
  • python嵌套函数使用外部函数变量的方法(Python2和Python3)

    2022-05-16 20:29:25
  • ASP如何输出字符

    2007-09-22 18:41:00
  • 十“问”DreamWeaver

    2007-02-03 11:39:00
  • python 在屏幕上逐字显示一行字的实例

    2023-09-22 22:55:29
  • python爬虫数据保存到mongoDB的实例方法

    2021-10-10 09:52:24
  • python编程简单几行代码实现视频转换Gif示例

    2021-09-02 03:34:13
  • asp之家 网络编程 m.aspxhome.com