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.py file, import the Flask class 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.
Creating a main entry point of the script for starting the Flask application at port 5000, enabling the debug mode.
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.py file, first import the Flask class and escape, then create an instance of the Flask class.
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 main entry point of the script for starting the Flask application at port 5001, enabling the debug mode.
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/1 and path/some/path. For suffix post/1, it displays message Post 1. For suffix path/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.py file, import the Flask class 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 called projects.
@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 /about with a view function called about.
@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 main entry point of the script for starting the Flask application at port 5002, enabling the debug mode.
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.py file, and first import Flask class and url_for. Also do not forget to create an instance of the Flask class.
from flask import Flask, url_for
app = Flask(__name__)
Use route() decorator to create three routes, and define corresponding view functions.
We use the test_request_context() method to try out url_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 function index, resulting in /.
url_for('login') generates a URL for the view function login, resulting in /login.
url_for('login', next='/') generates a URL for the view function login and includes an additional query parameter next, resulting in /login?next=/.
url_for('profile', username='John Doe') generates a URL for the view function profile with the username variable set to John Doe, resulting in /user/John%20Doe
Directly run the url_building.py file 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.
We use cookies for a number of reasons, such as keeping the website reliable and secure, to improve your experience on our website and to see how you interact with it. By accepting, you agree to our use of such cookies. Privacy Policy