1

I run bottle as part of an environment and cannot understand how to pass variables to its routing functions. The following code runs fine:

import bottle

class WebServer():
    message1 = 'hello message1'

    def __init__(self):
        self.message2 = 'hello message2'
        bottle.run(host='localhost', port=8080)

    @bottle.get('/hello')
    def hello():
        # here I would like to return message1 or message2
        return 'unfortunately only a static message so far'

WebServer()

I would like to return message1 or message2 (two separate cases) when calling the /hello URL. I do not know how to pass self to hello(), though. How should I do that?

WoJ
  • 27,165
  • 48
  • 180
  • 345

1 Answers1

1

Following up on ndpu's comment and on bottle documentation about explicit routing, I have rewritten the code as

import bottle

class WebServer():
    message1 = 'hello message1'

    def __init__(self):
        self.message2 = 'hello message2'
        bottle.run(host='localhost', port=8080)

    def hello(self):
        # here I would like to return message1 or message2
        # return 'unfortunately only a static message so far'
        # now it works
        return self.message1  # or self.message2

w = WebServer()
bottle.route('/hello', 'GET', w.hello)

This ended up being a cleaner way (IMHO) to structure the routing.

Unfortunately this does not seem to work for error routing. I did not find a way to turn the working

@bottle.error(404)
def error404(error):
    print('error 404')
    return

into something like the above (bottle.error...) - the relevant documentation mentions that this is a decorator (so I guess it has to stay as it is)

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