Python Pyramid 简明教程
Python Pyramid - Creating A Project Manually
Cookiecutter 工具使用预定义的项目模板自动生成项目和包结构。对于复杂项目,它在正确组织各种项目组件方面节省了大量的手动工作。
The Cookiecutter utility uses pre-defined project templates to auto-generate the project and package structure. For complex projects, it saves a lot of manual effort in properly organizing various project components.
但是,可以手动构建 Pyramid 项目,而不必使用 Cookiecutter。在本节中,我们将看到如何按照以下简单步骤构建名为 Hello 的 Pyramid 项目。
However, a Pyramid project can be built manually without having to use Cookiecutter. In this section, we shall see how a Pyramid project named Hello is built in following easy steps.
setup.py
在 Pyramid 虚拟环境中创建项目目录。
Create a project directory within Pyramid virtual environment.
md hello
cd hello
并将以下脚本另存为 setup.py
And save the following script as setup.py
from setuptools import setup
requires = [
'pyramid',
'waitress',
]
setup(
name='hello',
install_requires=requires,
entry_points={
'paste.app_factory': [
'main = hello:main'
],
},
)
如前所述,这是一个 Setuptools 设置文件,它定义了为软件包安装依赖项的要求。
As mentioned earlier, this is a Setuptools setup file that defines requirements for installing dependencies for your package.
运行以下命令来安装项目并在名称 hello.egg-info. 中生成“egg”
Run the following command to install the project and generate the 'egg' in the name hello.egg-info.
pip3 install -e.
development.ini
Pyramid 主要使用 PasteDeploy 配置文件来指定主应用程序对象和服务器配置。我们准备在 hello 包的 egg 信息和侦听 localhost 5643 端口的 Waitress 服务器中使用应用程序对象。因此,将以下代码段另存为 development.ini 文件。
Pyramid uses PasteDeploy configuration file mainly to specify the main application object, and the server configuration. We are going to use the application object in the egg info of hello package, and the Waitress server, listening on port 5643 of the localhost. Hence, save the following snippet as development.ini file.
[app:main]
use = egg:hello
[server:main]
use = egg:waitress#main
listen = localhost:6543
init.py
最后,应用程序代码位于此文件中,此文件对于识别 hello 文件夹为一个包至关重要。
Finally, the application code resides in this file which is also essential for the hello folder to be recognised as a package.
该代码是一个基本的 Hello World Pyramid 应用程序代码,具有 hello_world() 视图。 main() 函数将此视图注册到具有 '/' URL 模式的 hello 路由,并返回由 make_wsgi_app() 给出的 Configurator 方法的应用程序对象。
The code is a basic Hello World Pyramid application code having hello_world() view. The main() function registers this view with hello route having '/' URL pattern, and returns the application object given by make_wsgi_app() method of Configurator.
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('<body><h1>Hello World!</h1></body>')
def main(global_config, **settings):
config = Configurator(settings=settings)
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
return config.make_wsgi_app()
最后,使用 pserve 命令提供该应用程序。
Finally, serve the application with the help of pserve command.
pserve development.ini --reload