Python Flask Redirect and Errors (original) (raw)

A redirect is used to send a user from one URL to another. When a redirect occurs, server responds with an HTTP status code that instructs the browser to load a different location. Redirects are commonly used after form submissions, authentication checks or when a resource has moved.

Syntax

flask.redirect(location, code=302)

**Parameters:

**Return: a response object that redirects the user to the specified URL with the given HTTP status code.

HTTP Status Codes

HTTP status codes are three-digit numbers returned by the server to indicate how the request should be handled. The following codes are commonly associated with redirects:

Code Status
300 Multiple Choices
301 Moved Permanently
302 Found (Temporary Redirect)
303 See Other
304 Not Modified
305 Use Proxy
306 Reserved
307 Temporary Redirect

Importing redirect Function

To perform URL redirection, we need to import the redirect function from the Flask module:

from flask import redirect

The redirect() function returns a response that instructs the browser to navigate to a different URL.

Example: Redirecting Based on Login Input

In this example, we create a Flask application that redirects users based on the username entered in a login form.

**app.py

Python `

from flask import Flask, redirect, url_for, render_template, request app = Flask(name)

@app.route('/') def index(): return render_template("login.html")

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

@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'))

if name == 'main': app.run(debug=True)

`

HTML Template (login.html)

Create a templates folder in the project directory and add the following file inside templates/login.html

HTML `

Username:
Login

`

Run the Flask application using:

python app.py

**Output

main page

**Case 1: If the Username is admin and the method is POST then it will redirect to the success URL and display logged in successfully.

adding username as admin and click login

after clicking login button

**Case 2: If the username is anything other than admin, the application redirects back to the login page, allowing the user to enter the username again.

entering username other than admin

url_for() Function

url_for() function is used to dynamically generate URLs for a specific function. It takes the function name as the first argument and builds the corresponding URL. This is useful when performing redirects because it avoids hardcoding URLs and makes the application easier to maintain.

**Example: Here, the user(name) route checks whether the provided name is admin. If it matches, the request is redirected to the admin page. Otherwise, it redirects to the guest page.

Python `

from flask import Flask, redirect, url_for app = Flask(name)

@app.route('/admin') def hello_admin(): return 'Hello Admin'

@app.route('/guest/') def hello_guest(guest): return 'Hello %s as Guest' % guest

@app.route('/user/') def hello_user(name):

if name == 'admin':
    return redirect(url_for('hello_admin'))
else:
    return redirect(url_for('hello_guest', guest=name))

if name == 'main': app.run(debug=True)

`

**Output: When the URL is /user/admin, the application redirects to the admin page and displays:

When the URL is /user/Ayush, the application redirects to the guest page and displays:

The url_for() function ensures that URLs are generated dynamically, which helps keep routing flexible and prevents issues if route paths change later.

Flasks Errors

abort() function is used to stop request processing and return an HTTP error response. It is commonly used when a requested resource does not exist, request is invalid or access is not allowed.

Syntax

abort(code, message=None)

**Parameters:

When abort() is called, Flask immediately stops the current request and returns the specified error code to the client.

HTTP Error Codes

The following HTTP status codes are commonly used when handling errors in Flask applications:

**Code **Error
400 Bad request
401 Unauthenticated
403 Forbidden
404 Not Found
406 Not Acceptable
415 Unsupported Media Type
429 Too Many Requests

Examples

**Example 1: In this example, we check the username provided in the URL using Error Code 400. If username starts with a number, application raises an error using the abort() function. Otherwise, it returns a success message.

Python `

from flask import Flask, abort app = Flask(name)

@app.route('/') def index(uname): if uname[0].isdigit(): abort(400) return '

Good Username

'

if name == 'main': app.run()

`

**Output

**Case 1: If the username does not start with a number, the page displays:

if username doesnt start with a number

**Case 2: If the username starts with a number, Flask raises a 400 Bad Request error.

Flask Redirect and Errors

if username start with a number

**Example 2: In this example, error code in abort() is changed to 403. If the username starts with a number, the application raises a Forbidden error instead.

Python `

from flask import Flask, abort app = Flask(name)

@app.route('/') def index(uname): if uname[0].isdigit(): abort(403) return '

Good Username

'

if name == 'main': app.run()

`

**Output: If the username starts with a number, Flask returns a 403 Forbidden error. Otherwise, page displays "Good Username".

Flask Redirect and Errors

when username start with a number