anvd
anvd

Reputation: 4047

redirect in before_app_request

mod = Blueprint('users', __name__, url_prefix='/users')

@mod.route('/welcome')
def www():
    return '<h1>Hello</h1>'

@mod.before_app_request
def before_request():
    return redirect(url_for('www'))

This code give me this error:

  raise BuildError(endpoint, values, method)
BuildError: ('www', {}, None)

If I try this one, I will get an infinite loop redirect in the browser.

 return redirect(url_for('users.www'))

My question is, how can I redirect the before_app_request to another action?


EDIT: log after changes, Now the redirect works, but the error still exists.

http://sharetext.org/dDje

Upvotes: 2

Views: 2663

Answers (1)

metatoaster
metatoaster

Reputation: 18938

With the way you set this up pretty much every request for this blueprint, including one to 'users.www' - hence the infinite loop redirect. You need some kind of conditions so that it would learn not to redirect and load the /welcome endpoint.

Also, url_for('www') will not work as you intend as you need . prefix to reference the current blueprint. Check the documentation for url_for

Maybe something like:

@mod.before_app_request
def before_request():
    if request.endpoint != 'users.www':
        return redirect(url_for('.www'))

Do note that you might want to print out the request.endpoint and grab the exact one, I can't remember how they are flask handles/names them internally for blueprints.

Reference: flask before request - add exception for specific route

Upvotes: 3

Related Questions