03:应用程序配置 .ini 文件夹¶
使用Pyramid pserve 用A命令 .ini 配置文件,使应用程序运行更简单、更好。
背景¶
Pyramid有一个一流的概念 configuration 与代码不同。这种方法是可选的,但是它的存在使它不同于其他的python web框架。它进入了 Python 的 Setuptools 库,它为安装和为python项目提供“:term:entry points”建立约定。Pyramid使用 entry point 让Pyramid应用程序知道在哪里可以找到wsgi应用程序。
目标¶
修改我们的
setup.py有一个 entry point 告诉PyramidWSGi应用程序的位置。创建由
.ini文件。使用Pyramid启动应用程序
pserve命令。将代码移动到包的
__init__.py.
步骤¶
首先,我们复制上一步的结果:
cd ..; cp -r package ini; cd ini
我们的
ini/setup.py需要一个 Setuptools entry point 在setup()功能:1from setuptools import setup 2 3# List of dependencies installed via `pip install -e .` 4# by virtue of the Setuptools `install_requires` value below. 5requires = [ 6 'pyramid', 7 'waitress', 8] 9 10setup( 11 name='tutorial', 12 install_requires=requires, 13 entry_points={ 14 'paste.app_factory': [ 15 'main = tutorial:main' 16 ], 17 }, 18)
我们现在可以安装我们的项目,从而在
ini/tutorial.egg-info:$VENV/bin/pip install -e .
我们做个文件吧
ini/development.ini对于我们的配置:1[app:main] 2use = egg:tutorial 3 4[server:main] 5use = egg:waitress#main 6listen = localhost:6543
我们可以从上一步的
app.py进入之内ini/tutorial/__init__.py:1from pyramid.config import Configurator 2from pyramid.response import Response 3 4 5def hello_world(request): 6 return Response('<body><h1>Hello World!</h1></body>') 7 8 9def main(global_config, **settings): 10 config = Configurator(settings=settings) 11 config.add_route('hello', '/') 12 config.add_view(hello_world, route_name='hello') 13 return config.make_wsgi_app()
既然
ini/tutorial/app.py未使用,请删除它:rm tutorial/app.py运行 Pyramid 应用程序时使用:
$VENV/bin/pserve development.ini --reload
打开http://localhost:6543/。
分析¶
我们的 development.ini 文件被读取 pserve 并用于引导我们的应用程序。然后按照Pyramid章节中的描述进行处理 application startup :
pserve寻找[app:main]发现use = egg:tutorial.项目的
setup.py定义了一个 entry point (第10-13行)用于项目的“主要” entry point 属于tutorial:main.这个
tutorial包装的__init__有一个main功能。调用此函数,其中的值来自
.ini通过的部分。
这个 .ini 文件还用于其他两个功能:
配置wsgi服务器 .
[server:main]连接选择哪个WSGi 服务器 为您的WSGI 应用 . 在这种情况下,我们使用waitress我们在tutorial/setup.py安装在 要求 本教程开头的步骤。它还连接了 端口号 :listen = localhost:6543告诉waitress在主机上收听localhost在港6543.备注
运行命令
$VENV/bin/pip install -e .将检查我们的虚拟环境中以前安装的包,这些包在我们的包中指定setup.pyfile, then install our package in editable mode, installing any requirements that were not previously installed. If a requirement was manually installed previously on the command line or otherwise, in this case Waitress, then$VENV/bin/pip install -e .只会检查它是否已安装并继续。配置python日志记录 . Pyramid使用Python标准日志记录,这需要一些配置值。这个
.ini服务于此功能。这提供了在启动和每个请求时看到的控制台日志输出。
我们将启动代码从 app.py 到包的 tutorial/__init__.py . 这不是必需的,但在Pyramid中,将wsgi应用程序从模块的代码中引导出来并放入包中是一种常见的方式。 __init__.py .
这个 pserve 应用程序运行程序有许多命令行参数和选项。我们正在使用 --reload 它告诉 pserve 要监视文件系统中相关代码(python文件、ini文件等)的更改,并在发生更改时重新启动应用程序。开发时非常方便。
额外credit¶
如果您不喜欢配置和/或
.ini文件,你能用python代码自己做吗?我们能要多重的吗
.ini项目的配置文件?你为什么要这么做?这个 entry point 在里面
setup.py没有提到__init__.py当它宣布tutorial:main功能。为什么不呢?目的是什么
**settings?什么是**意味着?