Flask: URL Routes and Views (Pt.4)

Flask: URL Routes and Views (Pt.4)

A website's homepage can be found using the URL (Uniform Resource Locator, a website's address) hostname followed by /, /home, /about or something else that's easy to understand.

These URLs help users remember the URL and access it easily compared to when something like your about page is /7392-kw or /weird_stuff. Flask lets us use the route() decorator to connect a meaningful URL to each view function created.

View Functions

In my previous article about MTV architecture, we can recall that views are the visible components that the user interacts with. We created a function that acts as the view in Flask and in my previous article again, we can recall that this function was called hello. This function acted as the view and then it was bonded with a route.

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

In summary, correct me if I'm wrong though: route + function= view

The route() decorator

This decorator takes the following parameters:

  • rule: This represents the URL rule that's passed as a string to the decorator (a decorator is a function that takes another function and extends the function of the latter function without explicitly modifying it, more about this here).

  • endpoint: Developers don't need to specify this as Flask already assumes the parameter itself. endpoint is the name of the view function that's bound to the URL route.

  • options

Static routing

We use a specific URL string as a rule and give it to the route() decorator.

It is important to know that the rule is a case-sensitive string. Therefore, /Wonderwoman and /wonderwoman are actually different URLs.

Static URL routes example

In the example below, two static routes are specified and they have the URLs /home and /about

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def home():
    return "This is the homepage :)"

@app.route("/about")
def learn():
    return "All about Flask!"


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=3000)

I may have created another virtual environment for this one and named the new folder, flaskapp. I talked a bit about creating virtual environments for Flask in this article.

image.png

Fastforward

So, I typed in python -m flask run in the terminal, ctrl+click the link and I got:

image.png

image.png

Notice what happens when I append /about to the URL.

image.png

@app.route("/")
def home():
    return "This is the homepage :)"

home() view function corresponds to "/". It's the default route of web applications.

@app.route("/about")
def learn():
    return "All about Flask!"

learn() view function corresponds to the route "/about" which is why this view is called when you append "/about".

References:

- - - - - - - -

Thank you for reading! See you in my next post :)