【发布时间】:2018-02-23 22:11:23
【问题描述】:
我是金字塔的新手。尝试使用 chameleon 作为模板引擎时,在使用相对路径指定时找不到模板 - 它正在 env35/lib/python3.5/site-packages/pyramid/ 查找它,其中 env35 是我创建的虚拟环境。但是,如果指定了完整路径,它将起作用。它还可以使用 jinja2 作为模板引擎的相对路径。
为什么我不能使用相对路径的变色龙模板?
来自手册
add_view(...., 渲染器,...)
这是单个字符串术语(例如 json)或暗示路径或资产规范的字符串(例如模板/views.pt) 命名渲染器实现。如果渲染器值不 包含一个点.,指定的字符串将用于查找一个 渲染器实现,并且将使用该渲染器实现 从视图返回值构造响应。如果渲染器 value 包含一个点 (.),指定的术语将被视为 路径,路径中最后一个元素的文件扩展名将 用于查找渲染器实现,将通过 完整路径。渲染器实现将用于构造一个 来自视图返回值的响应。
请注意,如果视图本身返回响应(请参阅 View Callable Responses),则永远不会调用指定的渲染器实现。
当渲染器是一个路径时,虽然路径通常只是一个简单的相对路径名(例如,templates/foo.pt,暗示一个 名为“foo.pt”的模板位于相对于“模板”目录中 Configurator当前包的目录),路径可以 是绝对的,在 UNIX 上以斜杠开头,在 UNIX 上以驱动器号前缀开头 视窗。路径也可以是表单中的资产规范 some.dotted.package_name:relative/path,使得寻址成为可能 存在于单独包中的模板资产。
渲染器属性是可选的。如果未定义,则假定为“null”渲染器(不执行渲染,值为 未修改地传回上游 Pyramid 机器)。
这是我设置环境所采取的步骤...
export VENV=~/Documents/app_projects/pyramid_tutorial/env35
python3 -m venv $VENV
source $VENV/bin/activate #activate the virtual environment
pip install --upgrade pip
pip install pyramid
pip install wheel
pip install pyramid_chameleon
pip install pyramid_jinja2
我的文件结构:
pyramid_tutorial
env35
bin
...
templates
hello.jinja2
hello.pt
test_app.py
test_app.py:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config
def hello(request):
return dict(name='Bugs Bunny')
if __name__ == '__main__':
config = Configurator()
config.include('pyramid_chameleon')
config.include('pyramid_jinja2')
#This does not work... http://localhost:6543/chameleon
config.add_route('hello_world_1', '/chameleon')
config.add_view(hello, route_name='hello_world_1', renderer='templates/hello.pt')
# ValueError: Missing template asset: templates/hello.pt (/home/david/Documents/app_projects/pyramid_tutorial/env35/lib/python3.5/site-packages/pyramid/templates/hello.pt)
#This works... http://localhost:6543/chameleon2
config.add_route('hello_world_2', '/chameleon2')
config.add_view(hello, route_name='hello_world_2', renderer='/home/david/Documents/app_projects/pyramid_tutorial/templates/hello.pt')
#This works... http://localhost:6543/jinja
config.add_route('hello_world_3', '/jinja')
config.add_view(hello, route_name='hello_world_3', renderer='templates/hello.jinja2')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
print ('Serving at http://127.0.0.1:6543')
server.serve_forever()
你好.pt:
<p>Hello <strong>${name}</strong>! (Chameleon renderer)</p>
你好.jinja2:
<p>Hello <strong>{{name}}</strong>! (jinja2 renderer)</p>
【问题讨论】:
-
仅供参考,我们有一个 cookiecutter 可以促进该过程,并可以提供一个工作示例进行比较。我们也不推荐使用
activate。