Getting started with routes
Now that we have a basic understanding of how to set up a Flask application, let’s create a simple website with a few pages (routes).
Defining routes
In Flask, a route is a URL pattern that the application can respond to. When a user visits a URL, the application will execute the code associated with that URL. Routes are defined using the @app.route
decorator.
Assuming we are building a simple website with the following pages on the example.com
domain we can match up routes as follows:
@app.route("/")
- https://example.com/@app.route("/about")
- https://example.com/about@app.route("/contact")
- https://example.com/contact
Creating a simple website
Let’s create a simple website with the following routes:
- Home page (
/
) - About page (
/about
) - Contact page (
/contact
)
To add a new route we need a decorator and a function that returns the content for that route. It is best practice to name the function the same as the route.
Returning HTML content
While we have just been returning simple strings in our routes, we can also return HTML content. This allows us to create more complex web pages with styling and formatting.
Let’s update our routes to return HTML content:
Now when you visit the home page, about page, or contact page, you will see the HTML content returned by the routes.
- Home page 127.0.0.1:5000/ -
<h1>Welcome to the home page!</h1>
- About page 127.0.0.1:5000/about -
<h1>About us</h1><p>This is the about page.</p>
- Contact page 127.0.0.1:5000/contact -
<h1>Contact us</h1><p>Contact us at: <a href='mailto:contact@example.com'>contact@example.com</a></p>
Variable routes
In Flask, we can also define routes that accept variables. This allows us to create dynamic routes that can accept user input.
To define a variable route, we use <variable_name>
in the route pattern. The variable name is passed as an argument to the route function.
String Routes
Let’s create a route that accepts a username and displays a personalized greeting:
Now when you visit /user/john
, you will see the message Hello, john!
.
Integer Routes
We can also accept integers as variables:
Now when you visit /square/5
, you will see the message The square of 5 is 25.
.