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. 🎯
Flask is a lightweight web framework written in Python. It's perfect for beginners due to its simplicity and ease of use.
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. 💡
First, let's set up a new Flask project. Open your terminal, and run the following command:
pip install flaskNext, create a new file named app.py.
Let's create a simple Flask application that displays a "Hello, World!" message.
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!". 🎉
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.
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:
@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!".
What is Flask?
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! 📝