Cookiecutter工具使用預(yù)定義的項目模板來自動生成項目和包結(jié)構(gòu)。對于復(fù)雜的項目,它在正確組織各種項目組件方面節(jié)省了大量的手工工作。
然而,一個Pyramid項目可以手動建立,而不需要使用Cookiecutter。在本節(jié)中,我們將看到一個名為Hello的Pyramid項目是如何通過以下簡單步驟建立的。
在Pyramid虛擬環(huán)境中創(chuàng)建一個項目目錄。
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設(shè)置文件,定義了為你的軟件包安裝依賴項的要求。
運行下面的命令來安裝該項目,并生成名稱為 hello.egg-info 的’蛋’ 。
pip3 install -e.
Pyramid使用 PasteDeploy 配置文件主要是為了指定主要的應(yīng)用程序?qū)ο螅约胺?wù)器配置。我們將在 hello 包的蛋信息中使用應(yīng)用程序?qū)ο?,并使用Waitress服務(wù)器,監(jiān)聽本地主機的5643端口。因此,將下面的片段保存為development.ini文件。
[app:main]
use = egg:hello
[server:main]
use = egg:waitress#main
listen = localhost:6543
最后,應(yīng)用程序代碼駐留在這個文件中,這也是hello文件夾被識別為一個包所必需的。
該代碼是一個基本的Hello World Pyramid應(yīng)用程序代碼,具有 hello_world() 視圖。 main() 函數(shù)用具有’/’URL模式的hello路由注冊該視圖,并返回由Configurator的 make_wsgi_app() 方法給出的應(yīng)用程序?qū)ο蟆?/p>
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 命令的幫助下為該應(yīng)用程序提供服務(wù)。
pserve development.ini --reload
更多建議: