Introduction
Modern web applications use meaningful URLs to help users. Users are more likely to like a page and come back if the page uses a meaningful URL they can remember and use to directly visit a page. In this lab, we will focus on how to implement dynamic URLs and attach multiple rules to a function in Flask.
Route Decorator
In this step, you will use the route() decorator to bind multiple view functions with multiple URLs.
- Open the
route_decorator.pyfile, import theFlaskclass and create an instance of it.
from flask import Flask
app = Flask(__name__)
- Next we use the
route()decorator to create two routes,/and/hello, bind corresponding view functions, make them return Index Page and Hello, World respectively.
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
- Creating a
mainentry point of the script for starting the Flask application at port 5000, enabling thedebugmode.
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True)
- To run the application, first using the following commands to launched the Flask application in the terminal:
python3 route_decorator.py
Then open the "Web 5000" tab located at the top of the interface, refresh the page, and you can see the message Index Page.
For the route /hello, you can add the suffix hello directly in the URL bar above.

Then the page will display Hello, World message.
Variable Rules
In this step, you will add variable sections to a URL by marking sections with <variable_name>. Optionally, you can use a converter to specify the type of the argument like <converter:variable_name>.
- Open the
variable_rules.pyfile, first import theFlaskclass andescape, then create an instance of theFlaskclass.
from flask import Flask
from markupsafe import escape
app = Flask(__name__)
- In the
route()decorator, add<variable_name>and<converter:variable_name>patterns for creating dynamic URLs with variable sections. Let view functions return formatted strings.
@app.route('/user/<username>')
def show_user_profile(username):
## show the user profile for that user
return f'User {escape(username)}'
@app.route('/post/<int:post_id>')
def show_post(post_id):
## show the post with the given id, the id is an integer
return f'Post {post_id}'
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
## show the subpath after /path/
return f'Subpath {escape(subpath)}'
- Below is a table of common converter types:
| Type | Role |
|---|---|
string |
(default) accepts any text without a slash |
int |
accepts positive integers |
float |
accepts positive floating point values |
path |
like string but also accepts slashes |
uuid |
accepts UUID strings |
- Creating a
mainentry point of the script for starting the Flask application at port 5001, enabling thedebugmode.
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5001, debug=True)
- To run the application, first using the following commands to launched the Flask application in a new terminal:
python3 variable_rules.py
Then open the "Web 5001" tab located at the top of the interface, add the suffix user/Alice directly in the URL bar above.

Then the page will display User Alice message.
- You can also repeat the same operations for suffix
post/1andpath/some/path. For suffixpost/1, it displays message Post 1. For suffixpath/some/path, it displays message Subpath some/path.
Redirection Behavior
In this step, you will learn two rules differ in their use of a trailing slash.
- Open the
redirection_behavior.pyfile, import theFlaskclass and create an instance of it.
from flask import Flask
app = Flask(__name__)
- Use the
route()decorator to create a route called/projects/with a view function calledprojects.
@app.route('/projects/')
def projects():
return 'The project page'
The canonical URL for the projects endpoint has a trailing slash. It’s similar to a folder in a file system. If you access the URL without a trailing slash (/projects), Flask redirects you to the canonical URL with the trailing slash (/projects/).
- Create another route called
/aboutwith a view function calledabout.
@app.route('/about')
def about():
return 'The about page'
The canonical URL for the about endpoint does not have a trailing slash. It’s similar to the pathname of a file. Accessing the URL with a trailing slash (/about/) produces a 404 Not Found error. This helps keep URLs unique for these resources, which helps search engines avoid indexing the same page twice.
- Creating a
mainentry point of the script for starting the Flask application at port 5002, enabling thedebugmode.
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5002, debug=True)
- To run the application, first using the following commands to launched the Flask application in a new terminal:
python3 redirection_behavior.py
Then open the "Web 5002" tab located at the top of the interface, add the suffix projects directly in the URL bar above.

Then the page will display The project page message, cause it redirects to the route /projects/.
Add another suffix about/ instead of projects:

You should see Not Found message, which indicates a 404 Error. Change the suffix to about, then it can display the correct message The about page.
URL Building
In this step, you will use the url_for() function to build a URL to a specific function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters.
- Open the
url_building.pyfile, and first importFlaskclass andurl_for. Also do not forget to create an instance of theFlaskclass.
from flask import Flask, url_for
app = Flask(__name__)
- Use
route()decorator to create three routes, and define corresponding view functions.
@app.route('/')
def index():
return 'index'
@app.route('/login')
def login():
return 'login'
@app.route('/user/<username>')
def profile(username):
return f'{username}\'s profile'
- We use the
test_request_context()method to try outurl_for(). It tells Flask to behave as though it’s handling a request even while we use a Python shell.
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))
url_for('index')generates a URL for the view functionindex, resulting in/.url_for('login')generates a URL for the view functionlogin, resulting in/login.url_for('login', next='/')generates a URL for the view functionloginand includes an additional query parameternext, resulting in/login?next=/.url_for('profile', username='John Doe')generates a URL for the view functionprofilewith the username variable set toJohn Doe, resulting in/user/John%20Doe
- Directly run the
url_building.pyfile in a new terminal:
python3 url_building.py
it should output:
/
/login
/login?next=/
/user/John%20Doe
Summary
In this lab, we have learn various methods for making a meaningful URL, it is very important when we are designing a web application. By skillfully using Flask's routing capabilities, you can create organized and intuitive URLs that enhance the user's experience.



