BottlePy - 如何从钩子中找到当前路线?

时间:2013-01-24 10:46:50

标签: python python-3.x bottle

我在BottlePy中有以下挂钩:

@bottle_app.hook('before_request')
def update_session():
    # do stuff
    return

还有一些路线:

@bottle_app.route('/')
def index():
    return render('index')

@bottle_app.route('/example')
def example():
    return render('example')

update_session()开始,如何确定调用哪条路线?

我查看文档无济于事,但这肯定有可能吗?

2 个答案:

答案 0 :(得分:7)

请求包含bottle.routeroute.handle条目,两者都包含相同的值:

from bottle import request

print request['bottle.route']

没有记录;我必须找到它in the bottle.py source。该值为Route个实例;它具有.name.rule属性,您可以检查以确定匹配的路线。

if request['bottle.route'].rule == '/':
    # matched the `/` route.

对于您的具体示例,这可能是过度的,因为您只匹配简单路径,但对于具有正则表达式规则的更复杂规则,这比尝试匹配request.path属性更好(但它会是一个好主意是给你的路线name值。

答案 1 :(得分:1)

from bottle import request

@bottle_app.hook('before_request')
def update_session():
    print request.path
    return

应该做你想要的事情

然后,您可以将路线存储在字典中。

my_routes = {"/":lambda: 5}
event = my_routes.get(request.path, lambda: None)
print event()
相关问题