Flask redirects and errors
The Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with the specified status code.
The prototype of the redirect() function is as follows:
Flask.redirect(location, statuscode, response)
In the above function:
-
The location parameter is the URL to which the response should be redirected.
-
The statuscode is sent to the browser header, the default is 302.
-
The response parameter is used to instantiate the response.
The following status codes have been standardized:
- 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
The default status code is 302 , which means'found' .
Flask class has abort() function with error code
Flask.abort(code)
The Code parameter takes one of the following values:
-
400 -for bad request
-
401 -for unauthenticated
-
403 - Forbidden
-
404 -not less than
-
406 -Indicates not to accept
-
415 -Used for unsupported media types
-
429 -Too many requests
Let us make a slight change to the login() function in the above code . If you want to display the'Unauthurized' page, replace it with a call to abort(401) instead of redisplaying the login page.
Create python file url_redirect.py
from flask import Flask, redirect, url_for, render_template, request, abort
app = Flask(__name__)
@app.route('/')
def index():
return render_template('login.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)
Create a new template/login.html in the same level directory of the url_redirect.py file
<html>
<body>
<form action = "http://localhost:5000/login" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "username" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
Run the python file, then open the browser to visit http://127.0.0.1:5000/