python - 如何将 self 传递给 Bottle 路由函数?

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

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

最佳答案

跟进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提到这是一个装饰器(所以我想它必须保持原样)

关于python - 如何将 self 传递给 Bottle 路由函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20886551/

相关文章:

python - 模块在对象内部不可用(错误 : 'function' object has no attribute 'select' )

python 瓶: how to pass parameters into function handler

python - 如何通过 CherryPy 独立 Web 服务器启动 Bottle 应用程序?

python - 运行 Apache + Bottle + Python

python - 通过不可靠的互联网连接将本地收集的常规数据同步到在线数据库

python - PySpark 无法将 mariaDb 表中的值解码为整数

jsp - 将c:forEach变量传递给jsp:include

node.js - 在 AWS Lambda 上处理未初始化或错误的 Redis 连接

python - python - 不使用random.shuffle()随机化元组列表

python - 更好地替换巨大的 “if x==2/if x==3/if x==4” 链删除前缀和后缀?