1.

How to redirect a user to another endpoint? Explain how to handle errors for redirecting a user.

Answer»

Use the redirect() function to send a user to another endpoint; use the abort() function to abort a REQUEST early with an error code:

from flask IMPORT abort, redirect, url_for[Text Wrapping Break][Text Wrapping Break]@app.route('/')[Text Wrapping Break]def index():[Text Wrapping Break]    return redirect(url_for('login'))[Text Wrapping Break][Text Wrapping Break]@app.route('/login')[Text Wrapping Break]def login():[Text Wrapping Break]    abort(401)[Text Wrapping Break]    this_is_never_executed()

Because a user will be diverted from the index to a page they cannot access (401 denotes access forbidden), this is a fairly worthless example, but it demonstrates how it works.

For each error code, a black and white error page is DISPLAYED by default. You may use the errorhandler() decorator to personalize the error page:

from flask import render_template[Text Wrapping Break][Text Wrapping Break]@app.errorhandler(404)[Text Wrapping Break]def page_not_found(error):[Text Wrapping Break]    return render_template('page_not_found.html'), 404

Take note of the 404 that APPEARS following the render template() function. This TELLS Flask that the page's status code should be 404, which stands for "not found." By default, the value 200 is assumed, which means that everything went smoothly.



Discussion

No Comment Found