gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:39:22 25 4
gpt4 key购买 nike

我跑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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com