Johnston
Johnston

Reputation: 20844

Flask Get the url variables in a before request?

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.

Upvotes: 3

Views: 4665

Answers (2)

ShivaGaire
ShivaGaire

Reputation: 2801

Apart from the URL preprocessors as described above, another approach to get args passed to the URL explicitly will be to use this.

@app.before_request
def get_request_args():
    "Provides all request args"
    request_args = {**request.view_args, **request.args} if request.view_args else {**request.args}
    print('All Request args ',request_args)

More info in the documentation of request.args and request.view_args

Upvotes: 1

davidism
davidism

Reputation: 127180

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.

Upvotes: 10

Related Questions