Flask Get the url variables in a before request?

flask, python

Solution

Register a URL processor using `@app.url_value_preprocessor`, which takes the endpoint and values matched from the URL. The values dict can be modified, such as popping a value that won't be used as a view function argument, and instead storing it in the `g` namespace.

from flask import g

@app.url_value_preprocessor
def store_user_token(endpoint, values):
    g.user_token = values.pop('user_token', None)

The docs include a detailed example of using this for extracting an internationalization language code from the URL.

Problem

In Flask I have url rules with variables. For example: ``` my_blueprint.add_url_rule('/<user_token>/bills/',view_func=BillsView.as_view('bills')) ``` This is going to pass the `user_token` variable to the `BillsView`'s `get` and `post` methods. I am trying to intercept that `user_token` variable in the `before_request` of my blueprint. Here is my blueprint `before_request`: ``` def before_req(): ... ... my_blueprint.before_request(before_req) ``` The closest I have come is to use `request.url_rule`. But that does not give me the content of the variable. Just the rule that matches.

Original source