How to get current route

hello, is there a way to get the current route?

i expected request.endpoint to do it, but it gives the name of the handler function rather than the custom route name.

edit: worked out the following disgusting hack:

def add_route(handler, route, name):
    handler._route_name = name
    app.add_route(handler, route, name=name)

def current_route(request):
    return request.app.router.get(request)[0]._route_name

There is a request.path attribute that can use used to get the route in question for the current handler.

@app.route("/test")
def test(request):
    return json({
        "msg": request.path
    })

that works in your specific example because the route has the same name as the handler (modulo slashes).

if i had:

@app.route("/butterfly", name="turtle")
def monkey(request):
    print(request.path)  # "/butterfly"
    print(request.endpoint)  # "monkey"
    print(request.TODO) # "turtle"

i’m looking for turtle, but path gives me /butterfly.

My question is… why is your ‘name’ different than the path or the endpoint?

What’s the use case here, and why do not either path or endpoint work for it?

name parameter already exists; i’m not making a feature request for it.

the reason i am using that feature is because i automatically generate some kinds of similar routes. simplified, and just one of several examples (and no, neither blueprints nor middlewares look like good alternatives):

def add_route_with_locale(handler, route):
    def handler_with_language(language, **kwargs):
        return handler(**kwargs)
    app.add_route(handler_with_language, '/language/' + route)

now if i use this helper with a bunch of handlers, they will all be named ‘handler_with_language’ by default, which is useless for ‘url_for’. so i specific my own names.

i don’t know how to answer the last part of your question, path and endpoint don’t work because they do completely different things…? see my previous comment, path gives the url, and endpoint gives the handler name (which is the same as the default route name, if you don’t specify a custom one). i am looking for the route name…

1 Like

last ,how to do?same to you :grinning: