WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Flask – Redirect & Errors


Flask class has a redirect() work. Whenever called, it returns a reaction object and redirects the user to target objective area with specified status code.

Prototype of redirect() capacity is as beneath −

Flask.redirect(location, statuscode, reaction) 

In the above capacity −

  • location parameter is where reaction ought to be redirected.

  • statuscode sent to program's header, defaults to 302.

  • response parameter is utilized to instantiate response.

The following status codes are institutionalized −

  • 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

Flask class has abort() function with an error code.

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)

The Code parameter takes one of following values −

  • 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

Let us make a slight change in the login() function in the above code. Give us a chance to make a slight change in the login() work in the above code. Rather than re-showing the login page, if 'Unauthourized' page is to be shown, supplant it with call to abort(401).