53. Flask: Routing [EN] - MantsSk/CA_PTUA14 GitHub Wiki

What is routing?

Routing in Flask is the process where you define how the server of the application should respond to various HTTP requests such as "GET", "POST", "PUT", "DELETE", etc. In this lesson, we will focus on GET requests.

A GET request is one of the HTTP protocol methods used by a client (e.g., a web browser) to retrieve information from the server. When a client makes a GET request, it requests a specific resource (e.g., a page or data) from the server.

For example, by entering www.google.lt in a browser, you make a GET request and receive the result.

How do you define a route?

We define a route using the @app.route() decorator.

@app.route is a decorator used in Flask to associate URL routes with functions. When you use the @app.route decorator above a function, you specify which URL route should be associated with that function. For example:

from flask import Flask
from flask import Response

app: Flask = Flask(__name__)

@app.route('/first/')
def first_page():
    return 'My first page'

if __name__ == '__main__':
    app.run(debug=True)

Now, when you open the page - http://127.0.0.1:5000/first/ in your browser, you will see the text returned by your function.

If we want this function to trigger as soon as the page is opened, we can modify our code like this:

from flask import Flask
from flask import Response

app: Flask = Flask(__name__)

@app.route('/')
def first_page():
    return 'My first page'

if __name__ == '__main__':
    app.run(debug=True)

We changed the app.route from "/first/" to "/". This makes the main page (URL /) go to the first_page() function, which simply returns a greeting message.

We can also add an additional route, for example:

@app.route('/profile')
def profile():
    return 'Profile page of ...'

Now, when you open the page http://127.0.0.1:5000/profile/, you will see the text: "Profile page of...".

Dynamic Routes

Flask also allows creating dynamic routes that accept parameters in the URL. This is very useful when we have different data that we want to display on the same page but use the same route. We can enhance our "profile" route and function.

@app.route('/profile/<name>')
def profile(name):
    return f'Profile page of... {name}'

This code would create a route that accepts a username in the URL (/profile/) and provides a greeting message with that name.

If we visit http://127.0.0.1:5000/profile/tomas, we would see:

Profile page of tomas

If we visit http://127.0.0.1:5000/profile/mantas, we would see:

Profile page of mantas

As you can see, we display the parameter obtained from the URL.

Summary

In summary, Flask's routing system allows easy management of application navigation and customization of content for the user. By using the @app.route decorator, we can quickly create mappings between URLs and functions, thereby facilitating the development of web applications.

This structure helps maintain clean and accessible code, making it easier to review and maintain, as all the routes of the functions' actions are clearly defined.

Full lesson code:

from flask import Flask
from flask import Response

app: Flask = Flask(__name__)

@app.route('/')
def first_page():
    return 'My first page'

@app.route('/profile/<name>')
def profile(name):
    return f'Profile page of... {name}'

if __name__ == '__main__':
    app.run(debug=True)

Exercises

Note: As we won't include exercises in the next lesson, please create a separate Python file named exercise_app.py specifically for these exercises. This will keep the main app.py file clean and focused on the lesson content.

Exercise 1: Defining Routes in Flask

Exercise: Modify the Flask application (app.py) to include a route that accepts variable paths for product categories. For example, create a route that responds to URLs like "/products/electronics", "/products/clothing", etc., and returns a message indicating the selected product category. Test the newly defined route by accessing different product category URLs in your browser.

Exercise 2: More Dynamic Routes in Flask

Exercise: Enhance the existing Flask application (exercise_app.py) by creating a dynamic route for user profiles. Modify the profile() function to accept a username as a parameter in the URL and display a personalized greeting message with that name. Additionally, display a list of hobbies associated with each user. Use a dictionary to store user profiles and their corresponding hobbies.

⚠️ **GitHub.com Fallback** ⚠️