Django WSGI 架构解析:从入口配置到 WSGIHandler 源码
本文深入解析 Django 的 WSGI 应用程序入口机制。通过追踪 WSGI_APPLICATION 配置项,梳理从项目 wsgi.py 到 get_wsgi_application() 函数的调用链,最终定位至 WSGIHandler 类。详细分析了 WSGIHandler 如何继承 BaseHandler 并实现 __call__ 方法以符合 WSGI 规范,包括中间件加载、请求处理及响应返回的核心逻辑,帮助开发者理解 Django 处理 HTTP 请求的内部流程。
前言
WSGI 架构核心组件
WSGI 规范主要包含三个核心组件:服务器(Server)、应用程序(Application)以及中间件(Middleware)。在运行过程中,服务器负责接收客户端请求并调用应用程序进行处理。应用程序内部封装了具体的业务逻辑,其功能几乎无所不包,而中间件则在此过程中介入,对请求和响应进行预处理或后处理。
Django 中的应用程序
Django 应用程序配置与入口
任何符合 WSGI 标准的应用程序,必须是一个接收 status 和 response_headers 参数并可选接收 exc_info 参数的 start_response 函数,或者是一个定义了 __call__ 方法的类。Django 的 django.core.handlers 模块采用了后者,实现了 WSGIHandler 类作为应用程序入口。在此之前,我们需要了解在具体的 Django 项目中是如何指定这个 application 的。
在 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 源码实现分析
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 查看。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









