Suppose i have the following structure:
/root/user/login
I do the login in a blueprint:
app.register_blueprint(login_blueprint,url_prefix=prefix('/user'))
I can redirect to ".index":
@login_blueprint.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
#### this redirects me to '/root/user/'
redirect_to_index= redirect(url_for('.index'))
response = current_app.make_response(redirect_to_index)
# do the log in
return response
redirect_to_index=redirect(url_for('.index'))
response = current_app.make_response(redirect_to_index)
The redirect brings me to /root/user
:
redirect(url_for('.index'))
But how to get to /root
(which is up relative to the current url (..
)?
Another method you can use when performing redirects in Flask is the url_for() function. The way that url_for() works is instead of redirecting based on the string representation of a route, you provide the function name of the route you want to redirect to.
Python for web development using FlaskFlask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected. statuscode sent to browser's header, defaults to 302.
To use any Flask Blueprint, you have to import it and then register it in the application using register_blueprint() . When a Flask Blueprint is registered, the application is extended with its contents. While the application is running, go to http://localhost:5000 using your web browser.
You can pass url_for
the name of the endpoint function for /root/
.
For example, if you have:
@app.route('/root/')
def rootindex():
return "this is the index for the whole site."
elsewhere in your app, you can do:
redirect(url_for('rootindex'))
To cause a redirect here. When you put a .
in front of the string you pass to url_for
, that tells it to look for an endpoint in the current blueprint. By leaving the .
off, you tell it to look for a endpoint in the app
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With