如何将自己传递给瓶子路由功能?

时间:2014-01-02 15:50:10

标签: python scope bottle

我将bottle作为环境的一部分运行,无法理解如何将变量传递给其路由功能。以下代码运行正常:

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

我想在调用message1网址时返回message2/hello(两个不同的情况)。不过,我不知道如何将self传递给hello()。我该怎么做?

1 个答案:

答案 0 :(得分:1)

跟进ndpu的评论和bottle documentation about explicit routing,我已将代码重写为

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)

这最终成为一种更清洁的方式(恕我直言)来构建路由。

不幸的是,这似乎不适用于错误路由。我没有办法改变工作方式

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

如上所述(bottle.error ...) - the relevant documentation提到这是一个装饰者(所以我想它必须保持原样)

相关问题