Flask – Redirects and Errors explained – why are they important?
In this tutorial, we are going to learn about redirects and errors in flask. We are also going to learn about the importance of these in our webpage and how to implement them on our webpage.
Flask – Redirects
In flask, the redirect() function has many functions. It is used to redirect the user to a specified location with a specified code by returning a response object.
The code prototype is as follows –
Flask.redirect(location, statuscode, response)
Parameters in the above function are –
- location parameter decides where the URL will take the user to.
- statuscode defaults to 302, when sent to the browser’s header.
- response parameter is used to instantiate a response.
Following is a list of standardized statuscodes –
- HTTP_300_MULTIPLE_CHOICES
- HTTP_301_MOVED_PERMANENTLY
- HTTP_302_FOUND
- HTTP_303_SEE_OTHER
- HTTP_304_NOT_MODIFIED
- HTTP_305_USE_PROXY
- HTTP_306_RESERVED
- HTTP_307_TEMPORARY_REDIRECT
In the following example, the redirect() function is used to display the login page again and again, when the login attempt fails.
from flask import Flask, redirect, url_for, render_template, request # Initialize the Flask application app = Flask(__name__) @app.route('/') def index(): return render_template('log_in.html') @app.route('/login',methods = ['POST', 'GET']) def login(): if request.method == 'POST' and request.form['username'] == 'admin' : return redirect(url_for('success')) return redirect(url_for('index')) @app.route('/success') def success(): return 'logged in successfully' if __name__ == '__main__': app.run(debug = True)
Flask – Errors
For displaying error pages, Flask class has an abort() function.
The code prototype is as follows –
Flask.abort(code)
The following values are accepted by the code parameter –
- 400: for Bad Request
- 401: for Unauthenticated
- 403: for Forbidden
- 404: for Not Found
- 406: for Not Acceptable
- 415: for Unsupported Media Type
- 429: Too Many Requests
Now to understand the abort() function and how error pages work in flask, let us make slight changes to our above code. So, now the login() function instead of again displaying the login form, it will now display an ‘unauthenticated‘ page.
from flask import Flask, redirect, url_for, render_template, request, abort app = Flask(__name__) @app.route('/') def index(): return render_template('log_in.html') @app.route('/login',methods = ['POST', 'GET']) def login(): if request.method == 'POST': if request.form['username'] == 'admin' : return redirect(url_for('success')) else: abort(401) else: return redirect(url_for('index')) @app.route('/success') def success(): return 'logged in successfully' if __name__ == '__main__': app.run(debug = True)
I hope you understood what was explained in this tutorial. If you have any doubts or queries regarding anything described here, please feel free to comment them down below.
Also read:
Leave a Reply