Python Pyramid - 手动创建项目



Cookiecutter 实用程序使用预定义的项目模板来自动生成项目和包结构。对于复杂的项目,它可以节省大量手动努力来正确组织各种项目组件。

但是,Pyramid 项目可以手动构建,而无需使用 Cookiecutter。在本节中,我们将了解如何按照以下简单步骤构建名为 Hello 的 Pyramid 项目。

setup.py

在 Pyramid 虚拟环境中创建一个项目目录。

md hello
cd hello

并将以下脚本保存为 **setup.py**

from setuptools import setup

requires = [
   'pyramid',
   'waitress',
]
setup(
   name='hello',
   install_requires=requires,
   entry_points={
      'paste.app_factory': [
         'main = hello:main'
      ],
   },
)

如前所述,这是一个 Setuptools 设置文件,用于定义安装包依赖项的要求。

运行以下命令以安装项目并在名为 **hello.egg-info** 的名称下生成“egg”。

pip3 install -e.

development.ini

Pyramid 使用 **PasteDeploy** 配置文件,主要用于指定主应用程序对象和服务器配置。我们将使用 **hello** 包的 egg 信息中的应用程序对象,以及在 localhost 的 5643 端口上监听的 Waitress 服务器。因此,将以下代码段保存为 development.ini 文件。

[app:main]
use = egg:hello

[server:main]
use = egg:waitress#main
listen = localhost:6543

__init__.py

最后,应用程序代码驻留在此文件中,此文件对于 hello 文件夹被识别为包也至关重要。

该代码是一个基本的 Hello World Pyramid 应用程序代码,具有 **hello_world()** 视图。**main()** 函数将此视图注册到具有“/”URL 模式的 hello 路由,并返回由 Configurator 的 **make_wsgi_app()** 方法提供的应用程序对象。

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** 命令提供应用程序。

pserve development.ini --reload
广告

© . All rights reserved.