Flask Redirect & Errors

redirect(): returns a response object and
  redirects the user to another target location with specified status code
  (must import redirect from flask)

redirect(location, statuscode, response)

location: URL be redirected
statuscode: default is 302
response: used to instantiate response

standardized status code−
    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

example1:

vi templates/login2.html
<html>
  <body>

    <form action = "/check" method = "POST">

      <p>User Name <input type = "text" name = "Name"/></p>
      <p><input type = "submit" value = "Login"/></p>

    </form>

  </body>
</html>
vi login2.py
from flask import Flask, redirect, url_for, render_template, request

ap = Flask(__name__)

@ap.route('/login')
def login():
  return render_template('login2.html')

@ap.route('/check', methods = ['POST', 'GET'])
def check():

  if request.method == 'POST' and request.form['Name'] == 'admin':
    return redirect(url_for('success'))

  return redirect(url_for('login'), 301) #care this line when you login fail

@ap.route('/success')
def success():
  return 'logged in successfully'

if __name__ == '__main__':
  ap.run(host='0.0.0.0')
python login2.py

Error: error code in abort()
(must import abort from flask)

abort(code)

Code parameter 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

example2:

#to modify login2.py
cp login2.py login2_2.py
vi
login2_2.py
from flask import Flask, redirect, url_for, render_template, request, abort #add abort

@ap.route('/check', methods = ['POST', 'GET'])
def check():

   if request.method == 'POST':
      if request.form['Name'] == 'admin' :
         return redirect(url_for('success'))
      else: #care the else statement
         abort(401)

   return redirect(url_for('login'), 301)
python login2_2.py



Leave comments

authimage

Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved