Routing
What is Routing?
Routing simply means returning stuff when someone visits a specific URL on your site, which is called a route. For example, in the previous tutorial, we had one route: the /
route which was our home page. In this tutorial, we will learn a little bit more about routing with Flask.
Making Routes In Flask
In Flask, we create routes to handle what happens when the user goes to a particular address. For example, if we wanted to return "Hello World" every time the user visits the route localhost:8080/hello-world/
, we would type:
from flask import Flask
app = Flask(__name__)
@app.route("/hello-world")
def hello_world():
return "Hello World"
app.run(port=8080)
@app.route("/hello-world/")
is a decorator, which tells Python to change the behavior of the next function. Here, it makes Flask run the next function whenever we visit /hello-world
.
Then, we actually declare the function. The name of the function actually doesn't matter, but it's always good to have descriptive names.
Flask gets the return value of the shows it to the user. Now, when we visit https://localhost:8080/hello-world, we see Hello World.
We can have as many routes as we want. We can also put HTML in the text that we return.
URL Variables
In Flask, we can put variables in the URL of a route. For example:
from flask import Flask
app = Flask(__name__)
@app.route("/hello/<name>")
def hello_world(name):
return "Hello " + name + "!"
app.run(port=8080)
In the above code, whenever we go to localhost:8080/hello/Learnmonkey, we would see Hello Learnmonkey!. If we now go to localhost:8080/hello/John we would see Hello John!. As you can see, the text that is being displayed corresponds to the URL, but we didn't need to hard-code every single thing that the user might enter.
/page
vs /page/
There is a difference between /page
and /page/
. If use /page
, /page
will work but /page/
will not. However, if we use /page/
as the route, both /page
and /page/
will work.