Routing in Flask
Routing is one of the fundamental features of Flask. It allows developers to define URLs that correspond to specific functions in their application. Flask's @app.route decorator is used to define these routes. Additionally, Flask supports dynamic routing with variables to make URLs more flexible. This article provides a step-by-step guide with real examples.
Defining Routes Using @app.route
The @app.route decorator binds a URL to a Python function. Here's a simple example:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to the Home Page!"
@app.route("/about")
def about():
return "This is the About Page!"
if __name__ == "__main__":
app.run(debug=True)
Explanation:
- The
@app.route("/")defines the route for the home page. - The
@app.route("/about")defines the route for the about page.
When you visit http://127.0.0.1:5000/, the home page message is displayed. Similarly, http://127.0.0.1:5000/about displays the about page message.
Dynamic Routing with Variables
Dynamic routing allows you to include variables in the URL. These variables can be passed to the associated function for processing. Here's an example:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to the Home Page!"
@app.route("/user/")
def user_profile(username):
return f"Hello, {username}! Welcome to your profile."
@app.route("/post/")
def show_post(post_id):
return f"This is post number {post_id}."
if __name__ == "__main__":
app.run(debug=True)
Explanation:
- The
@app.route("/user/<username>")route accepts a dynamicusernamevariable. For example, visiting/user/Alicewill display "Hello, Alice! Welcome to your profile." - The
@app.route("/post/<int:post_id>")route accepts an integerpost_id. For example, visiting/post/42will display "This is post number 42."
Handling Multiple Routes for a Single Function
You can assign multiple routes to a single function. For example:
@app.route("/")
@app.route("/home")
def home():
return "Welcome to the Home Page!"
In this case, both / and /home will display the same content.
Run the Application
Save the code to a file (e.g., app.py) and run it using:
python app.py
Open your browser and navigate to the defined routes to see the results.
Conclusion
Routing in Flask is straightforward yet powerful. Using @app.route, you can easily define static and dynamic routes to create a flexible web application. Dynamic routing with variables enhances the capability to handle user-specific or data-driven URLs.