Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
How to Change Port in Flask app
Next article icon

We'll discuss redirects and errors with PythonFlask in this article. A redirect is used in the Flask class to send the user to a particular URL with the status code. conversely, this status code additionally identifies the issue. When we access a website, our browser sends a request to the server, and the server replies with what is known as the HTTP status code, which is a three-digit number, The different reasons for errors are:

  • Unauthorized access or poor request.
  • Unsupported media file types.
  • Overload of the backend server.
  • Internal hardware/connection error.

Syntaxof Redirect

flask.redirect(location,code=302)

Parameters:

  • location(str):the location which URL directs to.
  • code(int): The status code for Redirect.
  • Code: The default code is 302 which means that the move is only temporary.

Return:The response object and redirects the user to another target location with the specified code.

The different  types of HTTP codes are:

Code

Status

300Multiple_choices
301Moved_permanently
302Found
303See_other
304Not_modified
305Use_proxy
306Reserved
307Temporary_redirect

Import the redirect attribute

We can redirect the URL using Flask by importingredirect.Let's see how to import redirects from Flask

Python3
fromflaskimportredirect

Example:

Let's take a simple example to redirect the URL using a flask namedapp.py.

Python3
# importing redirectfromflaskimportFlask,redirect,url_for,render_template,request# Initialize the flask applicationapp=Flask(__name__)# It will load the form template which# is in login.html@app.route('/')defindex():returnrender_template("login.html")@app.route('/success')defsuccess():return"logged in successfully"# loggnig to the form with method POST or GET@app.route("/login",methods=["POST","GET"])deflogin():# if the method is POST and Username is admin then# it will redirects to success url.ifrequest.method=="POST"andrequest.form["username"]=="admin":returnredirect(url_for("success"))# if the method is GET or username is not admin,# then it redirects to index method.returnredirect(url_for('index'))if__name__=='__main__':app.run(debug=True)

login.html

Create a folder named templates. In the templates, creates a templates/login.html file. On this page, we will take input from the user of its username.

HTML
<!DOCTYPE html><htmllang="en"><body><formmethod="POST",action="\login">         Username:<inputname=usernametype=text></input><br><buttontype="submit">Login</button></form></body></html>

Now we will deploy our code.

python app.py

Output:

 

Case 1: If the Username isadminand the method isPOSTthen it will redirect to the success URL  and display logged in successfully.

 
 

Case 2: In the other case, if the Username is something like xyz or anything then it will redirect to theindexmethod i.e., it will load the form again until the username is admin.

 

Flasks Errors

If there is an error in the address or if there is no such URL then Flask has anabort() function used to exit with an error code.

Syntax of abort() method

Syntax:abort(code, message)

  • code: int, The code parameter takes any of the following values
  • message: str, create your custom message Error.

The different types of errors we can abort in the application in your Flask. 

Code

Error

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

Example to demonstrate abort

In this example, if the username starts with a number then an error code message will through, else on success "Good username" will be printed.

Example 1:

Python3
# importing abortfromflaskimportFlask,abort# Initialize the flask applicationapp=Flask(__name__)@app.route('/<uname>')defindex(uname):ifuname[0].isdigit():abort(400)return'<h1>Good Username</h1>'if__name__=='__main__':app.run()

Output:

Case 1: If the username doesn't start with a number.

 

Case 2: If the username starts with a number.

Flask Redirect and Errors
 

Example 2:

In the above Python code, the status code to the abort() is400, so it raises a Bad Request Error. Let's try to change the code to403. If the username starts with a number then it raises a Forbidden Error.

Python3
# importing abortfromflaskimportFlask,abort# Initialize the flask applicationapp=Flask(__name__)@app.route('/<uname>')defindex(uname):ifuname[0].isdigit():abort(403)return'<h1>Good Username</h1>'if__name__=='__main__':app.run()

Output:

Flask Redirect and Errors
 

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp