CherryPy与Cheetah插件+工具 - 空白页面

1 投票
1 回答
509 浏览
提问于 2025-04-18 12:08

CherryPy 总是返回空白页面,或者只显示我在控制器中返回的值。我重写了一个 Django 和 Jinja2 的版本,那个是可以正常工作的,而这个几乎和之前提到的版本一模一样,却不行。

我在工具部分做了一些调试,发现请求的主体(request.body)里填充了解析后的 HTML,但当控制器中设置为 pass 时,它并没有输出。如果我在控制器中返回 {'user':True},那么它会以简单的“User”形式显示出来。

通过网上的一些例子和 SickBeard 的代码,我得出了以下内容:

控制器:

class RootController(object):
    @cherrypy.expose
    @cherrypy.tools.render(template="page/home.html")
    def index(self):
        pass

工具:

class CheetahTool(cherrypy.Tool):
    def __init__(self):
        cherrypy.Tool.__init__(self, 'on_start_resource',
                               self._render,
                               priority=30)

    def _render(self, template=None, debug=False):
        if cherrypy.response.status > 399:
            return

        # retrieve the data returned by the handler
        data = cherrypy.response.body or {}
        template = cherrypy.engine.publish("lookup-template", template).pop()

        if template and isinstance(data, dict):
            for k,v in data:
                template.__setattr__(k, v)

            # dump the template using the dictionary
            if debug:
                try:
                    cherrypy.response.body = unicode(template).encode('utf-8', 'xmlcharrefreplace')
                except Exception as e:
                    from pprint import pprint
                    pprint(e.message)
            else:
                cherrypy.response.body = template.respond()

插件:

class PageTemplate(Template):
    """
    Thank you SickBeard
    """
    def __init__(self, base_dir, template, *args, **KWs):
        KWs['file'] = os.path.join(base_dir, template)
        super(PageTemplate, self).__init__(*args, **KWs)
        application = cherrypy.tree.apps['']
        config = application.config 
        self.sbRoot = base_dir
        self.sbHttpPort = config['global']['server.socket_port']
        self.sbHttpsPort = self.sbHttpPort
        self.sbHttpsEnabled = False
        if cherrypy.request.headers['Host'][0] == '[':
            self.sbHost = re.match("^\[.*\]", cherrypy.request.headers['Host'], re.X|re.M|re.S).group(0)
        else:
            self.sbHost = re.match("^[^:]+", cherrypy.request.headers['Host'], re.X|re.M|re.S).group(0)

        if "X-Forwarded-Host" in cherrypy.request.headers:
            self.sbHost = cherrypy.request.headers['X-Forwarded-Host']
        if "X-Forwarded-Port" in cherrypy.request.headers:
            self.sbHttpPort = cherrypy.request.headers['X-Forwarded-Port']
            self.sbHttpsPort = self.sbHttpPort
        if "X-Forwarded-Proto" in cherrypy.request.headers:
            self.sbHttpsEnabled = True if cherrypy.request.headers['X-Forwarded-Proto'] == 'https' else False

        self.sbPID = str(aquapi.PID)
        self.menu = [
            { 'title': 'Home',            'key': 'home'           },
            { 'title': 'Users',           'key': 'users'          },
            { 'title': 'Config',          'key': 'config'         },
        ]

    def render(self):
        return unicode(self).encode('utf-8', 'xmlcharrefreplace')


class CheetahTemplatePlugin(plugins.SimplePlugin):
    def __init__(self, bus, base_dir=None, base_cache_dir=None, 
                 collection_size=50, encoding='utf-8'):
        plugins.SimplePlugin.__init__(self, bus)
        self.base_dir = base_dir
        self.base_cache_dir = base_cache_dir or tempfile.gettempdir()
        self.encoding = encoding
        self.collection_size = collection_size

    def start(self):
        self.bus.log('Setting up Cheetah resources')
        self.bus.subscribe("lookup-template", self.get_template)

    def stop(self):
        self.bus.log('Freeing up Cheetah resources')
        self.bus.unsubscribe("lookup-template", self.get_template)
        self.lookup = None

    def get_template(self, name):
        """
        Returns Cheetah's template by name.
        """
        return PageTemplate(self.base_dir, name)

初始化:

        # Template engine tool
        from aquapi.web.tools.template import CheetahTool
        cherrypy.tools.render = CheetahTool()

        # Tool to load the logged in user or redirect
        # the client to the login page
        from aquapi.web.tools.user import UserTool
        cherrypy.tools.user = UserTool()


        from aquapi.web.controllers import RootController 
        webapp = RootController()

        # Let's mount the application so that CherryPy can serve it
        app = cherrypy.tree.mount(webapp, '/', os.path.join(self.base_dir, "app.cfg"))

        # Template engine plugin
        from aquapi.web.plugin.template import CheetahTemplatePlugin
        engine.cheetah = CheetahTemplatePlugin(engine, 
                                        os.path.join(self.base_dir, 'aquapi/web/templates'),
                                        os.path.join(self.base_dir, 'cache'))
        engine.cheetah.subscribe()

1 个回答

2

总的来说,我觉得你的代码片段有点过于复杂了。CherryPy 插件通常用于一些系统任务,比如在引擎启动时创建一个 PID 文件,停止时删除它,或者用于异步任务,比如在单独的线程中发送邮件。模板渲染是和请求处理同步进行的,所以我不太明白为什么要把这个逻辑从 CherryPy 工具中提取出来。CherryPy 中有一个类,叫做 cherrypy._cptools.HandlerWrapperTool,它展示了如何包装处理器返回值的建议方法。

我自己没有用过 Cheetah,所以我给的例子是基于 Jinja2 的。你只需要把模板引擎的实例改成 Cheetah,并且调整它的调用方式。其他的部分都是一样的。

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import os
import types

import cherrypy
import jinja2


path   = os.path.abspath(os.path.dirname(__file__))
config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 4
  }
}


class TemplateTool(cherrypy.Tool):

  _engine = None
  '''Jinja environment instance'''


  def __init__(self):
    viewLoader   = jinja2.FileSystemLoader(os.path.join(path, 'view'))
    self._engine = jinja2.Environment(loader = viewLoader)

    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 = u'/'.join(parts)

    data     = handler(*args, **kwargs) or {}
    renderer = self._engine.get_template(u'{0}.html'.format(template))

    return renderer.render(**data)


cherrypy.tools.template = TemplateTool()


class App:

  @cherrypy.expose
  def index(self):
    '''No renderer applied, CherryPy outputs dict keys'''
    return {'user': 123}

  @cherrypy.tools.template
  def auto(self):
    return {'user': 123}

  @cherrypy.tools.template(name = 'app/auto')
  def manual(self):
    return {'user': 234}


if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

在 Python 文件旁边,创建一个目录 view/app,然后在里面新建一个名为 auto.html 的文件,并把以下内容放进去。

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv='content-type' content='text/html; charset=utf-8' />
    <title>Test</title>
  </head>
  <body>
    <p>User: <em>{{ user }}</em></p>
  </body>
</html>

关于 TemplateTool 的一些说明。首先,你可以用它作为装饰器,有两种方式:一种是不调用,另一种是带上模板名称参数进行调用。你可以像使用其他 CherryPy 工具一样在配置中使用这个工具(例如,让所有控制器方法都渲染模板)。其次,根据约定优于配置的原则,如果没有提供模板名称,这个工具会使用 classname/methodname.html。最后,这个装饰器会暴露方法,所以你不需要在上面加 @cherrypy.expose

撰写回答