Before diving into routing, make sure you have Flask installed. If not, you can install it using pip.
Run the following command in your terminal:
pip install flask
Now, create a new project folder and navigate into it
mkdir flask_routing_app
cd flask_routing_app
Create a Python file named app.py
in your project folder and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Welcome to the Home Page!"
if __name__ == "__main__":
app.run(debug=True)
Run the Flask app with this command:
python app.py
Once the server is running, open your browser and navigate to http://127.0.0.1:5000/. You should see the message
Welcome to the Home Page!
Now, let’s add more routes to handle different pages. Modify your app.py
file
@app.route("/about")
def about():
return "This is the About Page."
@app.route("/contact")
def contact():
return "This is the Contact Page."
Flask allows you to create dynamic routes that capture values from the URL. This is useful for things like displaying user profiles or blog posts.
Modify app.py
to create a dynamic route:
@app.route("/user/<username>")
def user_profile(username):
return f"Hello, {username}!"
By default, Flask routes respond to GET requests. However, you can specify different HTTP methods like POST, PUT, or DELETE.
Let’s modify the app.py
file to include a POST route:
from flask import request
@app.route("/submit", methods=["POST"])
def submit():
name = request.form.get("name")
return f"Form submitted by {name}"
Flask allows you to pass variables to templates, which makes routing even more dynamic.
Let’s render the dynamic route data in an HTML template. Create a templates/
folder and add an index.html
file:
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h1>Welcome {{ username }}!</h1>
</body>
</html>
Update app.py
to use render_template and pass the username
variable:
from flask import render_template
@app.route("/user/<username>")
def user_profile(username):
return render_template("index.html", username=username)
In this guide, you’ve learned how to:
✅ Set up routing in Flask
✅ Create static and dynamic routes
✅ Handle different HTTP methods
✅ Pass variables to templates
Flask routing is a powerful tool that enables you to build dynamic web applications by mapping different URLs to Python functions. Now you’re ready to create more complex routes and interactive web applications using Flask! 🚀