使用Cherrypy.Tool()定义自定义Mako工具失败

时间:2013-03-11 18:17:07

标签: python cherrypy mako

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

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)

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

  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'

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

1 个答案:

答案 0 :(得分:0)

在我将自定义Mako加载程序分配给HandleEvent之后,需要导入我的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)