0
0
Flaskframework~30 mins

URL building with url_for in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
URL building with url_for in Flask
📖 Scenario: You are creating a simple Flask web app that has multiple pages. You want to build URLs dynamically using Flask's url_for function instead of hardcoding links. This helps keep your app flexible and easy to maintain.
🎯 Goal: Build a Flask app with two routes: / and /about. Use url_for to generate the URL for the about page inside the home page's HTML link.
📋 What You'll Learn
Create a Flask app with two routes: home and about
Use url_for inside the home route to build the URL for the about page
Return simple HTML strings from both routes
The home page should have a link to the about page using the URL built by url_for
💡 Why This Matters
🌍 Real World
Web developers use url_for to build URLs dynamically so links stay correct even if routes change. This avoids hardcoding URLs and reduces bugs.
💼 Career
Understanding url_for is essential for Flask developers to write maintainable and flexible web applications.
Progress0 / 4 steps
1
Set up the Flask app and home route
Import Flask from flask. Create a Flask app called app. Define a route for / with a function called home that returns the string 'Home Page'.
Flask
Need a hint?

Start by importing Flask and creating the app instance. Then add a route for the home page that returns a simple string.

2
Add the about route
Define a new route for /about with a function called about that returns the string 'About Page'.
Flask
Need a hint?

Add a new route for the about page that returns a simple string.

3
Import url_for and build URL in home route
Import url_for from flask. Inside the home function, use url_for('about') to get the URL for the about page. Return an HTML string with an anchor tag linking to this URL and the text 'About'.
Flask
Need a hint?

Import url_for and use it inside the home function to create a link to the about page.

4
Add app run block
Add the standard Flask app run block at the bottom: if __name__ == '__main__': and inside it call app.run(debug=True).
Flask
Need a hint?

Add the block to run the Flask app when the script is executed directly.