无法让樱桃派中的 Mako 引擎工作



我需要使用CherryPy和Mako模板引擎来设置服务器,尽管我无法让后者工作。

我开始集成>>此处的代码<lt;进入我的CherryPy工作设置。尽管最后,我只看到"Hello,${username}!"作为文本,而不是插入的变量。我通过搜索或谷歌找到的其他信息或例子也没有解决这个问题。

由于代码很长,我使用pastebin来显示它。

服务器.py

app/application.py<lt;我在那里放了索引模块的另一个版本,但我也在上面链接的集成示例中尝试了它。

content/index.html是一个简单的文件:

<html>
<body>
Hello, ${username}!
</body>
</html>

有什么是我没有设置好的吗?

我在评论中建议您做的实际上只是更改模板引擎实例。其余的都是一样的。有一个CherryPy工具来处理模板例程是非常方便的,并且在配置方面提供了很大的灵活性。

#!/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

<!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关键字decorator参数重新定义模板
  • decorator暴露了您的方法本身,无需使用cherrypy.expose进行装饰
  • 您可以将该工具与配置中的任何其他CherryPy工具一样使用,例如,使/app/some/path下的所有方法都使用相应的模板来渲染数据

最新更新