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
廣告