您的位置:首页 > 编程语言 > Go语言

django源码分析 -- django启动初始化过程分析

2015-04-18 16:12 956 查看
django在启动之前会有一系列初始化过程。本文主要通过阅读django源码来探索django的初始化过程。

实现wsgi规范

django遵循wsgi规范,下面看一django的实现方式。

规范要求一 — 生成一个可调用对方给服务器调用

在django文档中有下面一句话

The key concept of deploying with WSGI is the application callable which the application server uses to communicate with your code. It’s commonly provided as an object named application in a Python module accessible to the server.

The startproject command creates a file <project_name>/wsgi.py that contains such an application callable.

It’s used both by Django’s development server and in production WSGI deployments.

WSGI servers obtain the path to the application callable from their configuration. Django’s built-in servers, namely the runserver and runfcgi commands, read it from the WSGI_APPLICATION setting. By default, it’s set to <project_name>.wsgi.application, which points to the application callable in <project_name>/wsgi.py.


再看代码 当使用django工具生成一个python项目时 会在项目文件下生成一个名为 wsgi.py的文件,代码如下

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tblog.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


不同项目 内容会略有不同。注意最下一行 有一个application 对象 那么这个对象就返回给服务器调用的课调用对象。

初始化代码

根据上面代码, 可调用对象是由get_wsgi_application函数生成并返回的 , 那么再看这个函数的代码

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.

"""
django.setup()
return WSGIHandler()


由上面的return可知,django返回对象就是一个WSGIHandler对象。上面的代码中调用setup函数就是django的初始化代码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: