URL Routes and Views

In this lesson, we will get to know what views are, and how they are associated with the URL routes. We will also learn how to create static routes.

Introduction

The homepage of a website can usually be found at the URL hostname followed by /, /home, /index or something self-explanatory.

These kinds of URLs enable the users to remember the URL and access it easily. It would be unexpected if the homepage were at a random URL such as /39283@&3911 or /more_eggs.

Flask allows us to use the route() decorator to bind a meaningful URL to each view function we create.

What is a view function?

In Flask, we create a function that acts as the view. Then, we bond it with a route.

@app.route("/")
def hello():
    return "Hello World!";

📌 Note: In developer circles, this function and the route combined is commonly referred to as the view or just simply the route. We will be using these terms interchangeably.

The route() decorator

The route decorator takes the following parameters:

  • rule: The rule represents the URL rule which is passed as a string to the decorator.
  • endpoint (not needed): The endpoint is the name of the view function which is bound to the URL route. Flask assumes this parameter itself, and the developer does not need to specify it.
  • options (optional): The options are an optional parameter.

💡 FYI: If you are unfamiliar with the concept of decorators, please refer to the Python docs at PEP318.

Static routing

In static routing, we specify a constant URL string as a rule to the route() decorator. For example in the mini-application given below, we have specified two static routes having URLs / and /educative respectively.

📌 Note: The rule is a case-sensitive string. Therefore, /educative and /Educative are totally different URLs.

An example using static URL routes

Get hands-on with 1400+ tech skills courses.