python – BottlePy – 如何在钩子中找到当前路径?

我在
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()中,如何确定调用哪条路由?

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

最佳答案 请求同时包含bottle.route和route.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属性更好(但是给出它是个好主意)你的路线名称值).

点赞