无法在CherryPy中使Mako引擎正常工作 [英] Can't get Mako engine in CherryPy to work
问题描述
我需要使用CherryPy和Mako模板引擎来设置服务器,尽管我无法使后者工作.
I need to set up a server using CherryPy and the Mako Template Engine, though I can't get the latter to work.
我开始将 >>此处<< 中的代码集成到我的工作CherryPy设置中.尽管最后,我只看到你好,$ {username}!"作为文本而不是插入的变量.我在搜索或Google上找到的其他信息或示例也无法解决该问题.
I started to integrate the code from >>here<< into my working CherryPy setup. Though in the end, I only see "Hello, ${username}!" as text instead of the inserted variable. Other information or examples I found via search or Google didn't solve that as well.
由于代码很长,因此我使用pastebin进行显示.
Since the code is quite long, I use pastebin to show it.
app/application.py <<我在其中放置了另一个版本的索引模块,但在上面链接的集成示例中也尝试使用了它.
app/application.py << I put another version of the index module there, but I also tried it with on in the integration example linked above.
content/index.html是这个简单的文件:
The content/index.html is this simple file:
<html>
<body>
Hello, ${username}!
</body>
</html>
有什么我设置不正确的东西吗?
Is there anything I didn't setup right?
推荐答案
我在注释中建议您执行的操作实际上只是对模板引擎实例的更改.其余部分相同.拥有CherryPy工具来处理模板例程非常方便,并为您提供了极大的配置灵活性.
What I suggested you to do in the comment was in fact just a change of template engine instance. The rest is the same. Having a CherryPy tool to handle templating routine is very handy and gives you big flexibility at configuration.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import types
import cherrypy
import mako.lookup
path = os.path.abspath(os.path.dirname(__file__))
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 8080,
'server.thread_pool' : 8
}
}
class TemplateTool(cherrypy.Tool):
_engine = None
'''Mako lookup instance'''
def __init__(self):
viewPath = os.path.join(path, 'view')
self._engine = mako.lookup.TemplateLookup(directories = [viewPath])
cherrypy.Tool.__init__(self, 'before_handler', self.render)
def __call__(self, *args, **kwargs):
if args and isinstance(args[0], (types.FunctionType, types.MethodType)):
# @template
args[0].exposed = True
return cherrypy.Tool.__call__(self, **kwargs)(args[0])
else:
# @template()
def wrap(f):
f.exposed = True
return cherrypy.Tool.__call__(self, *args, **kwargs)(f)
return wrap
def render(self, name = None):
cherrypy.request.config['template'] = name
handler = cherrypy.serving.request.handler
def wrap(*args, **kwargs):
return self._render(handler, *args, **kwargs)
cherrypy.serving.request.handler = wrap
def _render(self, handler, *args, **kwargs):
template = cherrypy.request.config['template']
if not template:
parts = []
if hasattr(handler.callable, '__self__'):
parts.append(handler.callable.__self__.__class__.__name__.lower())
if hasattr(handler.callable, '__name__'):
parts.append(handler.callable.__name__.lower())
template = '/'.join(parts)
data = handler(*args, **kwargs) or {}
renderer = self._engine.get_template('{0}.html'.format(template))
return renderer.render(**data)
cherrypy.tools.template = TemplateTool()
class App:
@cherrypy.tools.template
def index(self):
return {'foo': 'bar'}
@cherrypy.tools.template(name = 'app/index')
def manual(self):
return {'foo': 'baz'}
@cherrypy.tools.json_out()
@cherrypy.expose
def offtopic(self):
'''So it is a general way to apply a format to your data'''
return {'foo': 'quz'}
if __name__ == '__main__':
cherrypy.quickstart(App(), '/', config)
沿着脚本创建目录树 view/app
,在其中创建 index.html
:
Along the script create directory tree view/app
, create index.html
there with:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=utf-8' />
<title>Test</title>
</head>
<body>
<p>Foo is: <em>${foo}</em></p>
</body>
</html>
有关该工具的说明:
- 装饰器对模板文件名使用约定约定.它是
classname/methodname.html
.有时候,您可能想使用name
关键字装饰器参数重新定义模板. - 修饰器公开您的方法本身,无需使用
cherrypy.expose
, 进行修饰 - 您可以将该工具用作配置中的任何其他CherryPy工具,例如使
/app/some/path
下的所有方法使用相应的模板呈现数据.
- The decorator uses convention-over-configuration for template file name. It is
classname/methodname.html
. On occasion you may want to redefine the template withname
keyword decorator argument. - The decorator expose your method itself, no need to decorate with
cherrypy.expose
, - You can use the tool as any other CherryPy tool in the configuration e.g. to make all methods under
/app/some/path
to render data with corresponding templates.
这篇关于无法在CherryPy中使Mako引擎正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!