首页 > 解决方案 > CherryPy 工具:如何正确注册自定义工具?

问题描述

我想创建一个简单的工具,但无法正确注册。一旦我将它添加到任何方法中,我都会收到错误:

AttributeError: 'Toolbox' object has no attribute 'authenticate'

我试过了

cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)

@cherrypy.tools.register('before_handler')
def authenticate():

我可能遇到的问题是将函数放在错误的位置。我有一个启动服务器和所有应用程序的主文件:

#config stuff

if __name__ == '__main__':
    cherrypy.engine.unsubscribe('graceful', cherrypy.log.reopen_files)
    logging.config.dictConfig(LOG_CONF)
    cherrypy.tree.mount(app1(), '/app1')
    cherrypy.tree.mount(app2(), '/app2')
    cherrypy.quickstart(app3)

该文件由 systemd 单元启动。

如果我把这个authenticate功能放在配置区域,它就不起作用。如果我直接将它放在其中一个应用程序中并且只在该应用程序中使用它,它就不起作用。总是同样的错误。

那么我必须把它放在哪里才能完成这项工作呢?

标签: cherrypy

解决方案


我陷入python定义顺序陷阱的另一个案例。

不起作用:

class MyApp(object): 

    #....

@cherrypy.tools.register('on_start_resource')
def authenticate():
    #....

作品:

@cherrypy.tools.register('on_start_resource')
def authenticate():
    #....

class MyApp(object):

推荐阅读