BottlePy - How to find the current route from the hook?

I have the following hook in BottlePy :

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

      

And some routes:

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

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

      

Internally update_session()

, how can I determine which route is being called?

I've looked at the documentation to no avail, but is it possible?

+3


source to share


2 answers


The request has both an entry bottle.route

and route.handle

both contain the same value:

from bottle import request

print request['bottle.route']

      

This is not documented; I needed to find in the sourcebottle.py

. The value is an instance Route

; it has an attribute .name

and .rule

, which you could check to determine which route was matched.



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

      

In your specific example, this is probably too large as you are only using simple paths, but for more complex rules with regex rules this will work better than trying to match an attribute request.path

(but it would be a good idea to give your routes a value name

).

+6


source


from bottle import request

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

      

Gotta do what you ask



Then you can store the routes in the dictionary.

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

      

+1


source







All Articles