codecamp

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 的’蛋’ 。

pip3 install -e.

development.ini

Pyramid使用 PasteDeploy 配置文件主要是为了指定主要的应用程序对象,以及服务器配置。我们将在 hello 包的蛋信息中使用应用程序对象,并使用Waitress服务器,监听本地主机的5643端口。因此,将下面的片段保存为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


Pyramid 包结构
Pyramid 命令行Pyramid
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }