1

I wrap Bottle in a class and would like to bottle.route() error handlers. Is this possible? I currently use decorators on unbound functions as described in the docs (the comments reflect how I would like to change the code)

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()

Note: I read the warning in another SO thread about not doing the routing in __init__ but I will be using only one instance of the class.

Community
  • 1
  • 1
WoJ
  • 27,165
  • 48
  • 180
  • 345

1 Answers1

0

You should be able to define your error handler within 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()
ron rothman
  • 17,348
  • 7
  • 41
  • 43