0

我正在尝试通过以下内容在我的 cherrpy 服务器中定义我的自定义 Mako 加载程序server.py

from my.path.templating import MakoLoader
from HandleEvent import HandleEvent

cherrypy.tools.mako = cherrypy.Tool('on_start_resource', MakoLoader(os.path.join(os.path.dirname(__file__), 'templates')))

root = HandleEvent()

conf = { '/' : { 'request.dispatch' : cherrypy.dispatch.MethodDispatcher()}}

app = cherrypy.tree.mount(root, '/', conf)

然后我尝试使用自定义 mako 加载器作为我的HandleEvent类的装饰器,如下所示:

  class HandleEvent(object):
        exposed = True

    @cherrypy.tools.mako(template="template.html")
    def GET(self, **urlParams):
        return 'It worked!'

但是,当我尝试启动服务器时,出现以下错误:

Traceback (most recent call last):
  File "/usr/local/bin/cherryd", line 5, in <module>
    pkg_resources.run_script('CherryPy==3.1.2', 'cherryd')
  File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 461, in run_script
    self.require(requires)[0].run_script(script_name, ns)
  File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1194, in run_script
    execfile(script_filename, namespace, namespace)
  File "/usr/local/lib/python2.6/dist-packages/CherryPy-3.1.2-py2.6.egg/EGG-INFO/scripts/cherryd", line 95, in <module>
    options.imports)
  File "/usr/local/lib/python2.6/dist-packages/CherryPy-3.1.2-py2.6.egg/EGG-INFO/scripts/cherryd", line 15, in start
    exec "import %s" % i
  File "<string>", line 1, in <module>
  File "/var/my/path/server.py", line 4, in <module>
    from my.path.HandleEvent import http_methods_allowed
  File "/var/my/path/HandleEvent.py", line 63, in <module>
    class handleEvent(object):
  File "/var/my/path/HandleEvent.py", line 76, in HandleEvent
    @cherrypy.tools.mako(template="template.html")
AttributeError: 'Toolbox' object has no attribute 'mako'

我不确定为什么会发生这种情况,因为我之前以这种方式定义了这个自定义加载器。任何见解将不胜感激。

4

1 回答 1

0

在我HandleEvent将自定义 Mako 加载器分配给cherrypy.tools.mako. 所以正确的代码如下:

from my.path.templating import MakoLoader

cherrypy.tools.mako = cherrypy.Tool('on_start_resource', MakoLoader(os.path.join(os.path.dirname(__file__), 'templates')))

# The import should come here
from HandleEvent import HandleEvent
root = HandleEvent()

conf = { '/' : { 'request.dispatch' : cherrypy.dispatch.MethodDispatcher()}}

app = cherrypy.tree.mount(root, '/', conf)
于 2013-06-10T05:27:52.173 回答