Launching the Application

Pyramid 和 Pylons 的启动是一样的,因为它们都使用了PasteDeploy及其ini格式的配置文件。尽管 Pyramid 1.3用它自己的“pserver”命令替换了“贴纸服务”,这也是真的。“pserver”和“paster serve”都执行以下操作:

  1. Read the INI file.

  2. 基于“[app:main]”节实例化应用程序。

  3. 基于“[服务器:主]”部分实例化服务器。

  4. 根据日志部分配置python日志记录。

  5. Call the server with the application.

步骤1-3和5基本上是围绕PasteDeploy的包装器。只有第2步才是真正的“使用Pyramid”,因为只有应用程序依赖于Pyramid的其他部分。其余的程序是直接从“贴纸服务”复制,不依赖于Pyramid的其他部分。

启动程序实例化应用程序的方式经常被误解,所以让我们停下来详细说明一下。以下是Akhet演示中的应用程序部分:

[app:main]
use = egg:akhet_demo#main
pyramid.reload_templates = true
pyramid.debug_authorization = false

The "use=" line indirectly names a Python callable to load. "egg:" says to look up a Python object by entry point. (Entry points are a feature provided by Setuptools, which is why Pyramid/Pylons require it or Distribute to be installed.) "akhet_demo" is the name of the Python distribution to look in (the Pyramid application), and "main" is the entry point. The launcher calls pkg_resources.require("akhet_demo#main") 在SETUPTOOLS中,SETUPTOOLS返回python对象。入口点在发行版的setup.py中定义,安装程序将其写入入口点文件。这里是 akhet_demo.egg-info/entry_points.txt 文件:

[paste.app_factory]
main = akhet_demo:main

"paste.app_factory" is the entry point group, a name publicized in the PasteDeploy docs for all applications that want to be compatible with it. "main" (on the left side of the equal sign) is the entry point. "akhet_demo:main" says to import the akhet_demo package and load a "main" attribute. 这是我们的 main() function defined in akhet_demo/__init__.py. The other options in the "[app:main]" section become keyword arguments to this callable. These options are called "settings" in Pyramid and "config variables" in Pylons. (The options in the "[DEFAULT]" section are also passed as default values.) Both frameworks provide a way to access these variables in application code. In Pyramid they're in the request.registry.settings 在 Pylons 上,他们在 pylons.config 魔术全球。

启动程序以相同的方式加载服务器,使用“[服务器:主]”部分。

More details: The heavy lifting is done by loadapp()loadserver() 在里面 paste.deploy.loadwsgi . loadwsgi是钝的和未记录的,但是 pyramid.paster has some convenience functions that either call or mimic some of its routines.

其他启动程序,如mod wsgi,只读取“[app:main]”部分,忽略服务器部分,但它们仍在使用PasteDeploy或等效程序。也可以在不使用ini文件或pastedeploy的情况下手动实例化应用程序,我们将在“主函数”一章中看到这一点。

现在我们了解了更多关于启动器如何加载应用程序的信息,让我们更仔细地看看Pyramid应用程序本身。