是否可以将错误路由到类包装的Bottle方法?

时间:2014-07-31 15:41:36

标签: python bottle

我将Bottle包装在一个类中,并希望bottle.route()错误处理程序。这可能吗?我目前在文档中描述的未绑定函数上使用装饰器(注释反映了我想如何更改代码)

import bottle

class WebServer(object):
    def __init__(self):
        self.message = "hello world"
        bottle.route("/", 'GET', self.root)
        # bottle.route(error 404 to self.error404)
        bottle.run(host='0.0.0.0', debug=True)

    def root(self):
        print("hello from root")

    @bottle.error(404)
    def error404(error):
        # I would like to print self.message here after the routing above
        print("error 404")
        return

if __name__ == "__main__":
    WebServer()

注意:我读了the warning in another SO thread关于没有在__init__中进行路由的问题,但我将只使用该类的一个实例。

1 个答案:

答案 0 :(得分:0)

您应该能够在Webserver.__init__中定义错误处理程序:

import bottle

class WebServer(object):
    def __init__(self):
        self.message = "hello world"
        bottle.route("/", 'GET', self.root)

        # just define your error function here,
        # while you still have a reference to "self"
        @bottle.error(404)
        def error404(error):
            # do what you want with "self"
            print(self.message)
            return self.message

        bottle.run(host='0.0.0.0', debug=True)

    def root(self):
        print("hello from root")

if __name__ == "__main__":
    WebServer()