Flask Tutorials: Basic Routing (@app.route)

beginner
21 min

Flask Tutorials: Basic Routing (@app.route)

Welcome to the first lesson in our Flask tutorial series! Today, we'll dive into the world of Flask routing. By the end of this lesson, you'll be able to create your own web applications using Flask. 🎯

What is Flask?

Flask is a lightweight web framework written in Python. It's perfect for beginners due to its simplicity and ease of use.

Why use Flask routing?

Routing is a mechanism that helps Flask understand how to respond to different requests. It allows us to define URLs (web addresses) and the corresponding functions to handle them. 💡

Setting up our project

First, let's set up a new Flask project. Open your terminal, and run the following command:

bash
pip install flask

Next, create a new file named app.py.

Our first Flask app

Let's create a simple Flask application that displays a "Hello, World!" message.

python
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' if __name__ == '__main__': app.run(debug=True)

In the code above, we've imported Flask and created an instance of it. Then, we defined a route / which maps to the hello_world function. When you run this application, navigating to http://localhost:5000 in your web browser will display "Hello, World!". 🎉

Exploring @app.route

The @app.route decorator is used to define routes in Flask. It takes a string as an argument, which is the URL pattern that the function will handle. For example, the hello_world function we created earlier handles the / URL pattern.

Dynamic routing

Sometimes, we might want to create URLs that include dynamic parts, such as a user ID or a post title. Flask supports this through variables in the URL pattern. Here's an example:

python
@app.route('/user/<username>') def user(username): return f'Hello, {username}!'

In this example, <username> is a variable that will be replaced with the value from the requested URL. For example, http://localhost:5000/user/alice will return "Hello, Alice!".

Quiz Time!

Quick Quiz
Question 1 of 1

What is Flask?

Summary

In this lesson, we learned about routing in Flask and how to use the @app.route decorator to define routes. We also created our first Flask application and explored dynamic routing.

In the next lesson, we'll learn about handling form data and working with templates in Flask. Stay tuned! 📝