Saturday, September 24, 2022

Flask Tutorial for beginners - Part 6

FLASK ROUTES

Let's take a short pause and talk about a really important topic. ROUTES.

A route is a PATH taken. What is the path? The path is the part of the URL (or website link) after the domain name. The URL is the address of the webpage. URL stands for Uniform Resource Locator and you can do a Google or Yahoo! search if you want to get more information on it.

Let's continue.

For example, let's assume that your domain name is my.website.com. If you type in the following URL in your browser (http://my.website.com) you should get the home page of the website.

In Flask, the home page is represented by the backslash = /. In fact, the website receives the following route: http://my.website.com/ (note the backslash at the end)

Now here's another request to your website: http://my.website.com/login.

In that request the route is /login

And here's another request: http://my.website.com/contact.

In that request the route is /contact.

In a Python/Flask application, when the app receives the URL, it looks at the route and then passes it to a Python function to handle the request. Therefore in your app, you must write functions for all the requests you will receive. If you have a login page with the URL http://my.website.com/login, you must provide a route for /login. If you have a contact form which visitors access via the URL http://my.website.com/contact, you must also provide a function for the route /contact.

Here's a simple example of how an app can handle a login request.


Note two changes:
  1. We have added another import on line 1 = render_template. This is a special utility from Flask that allows us to quickly load a html template. We will see that later.
  2. We have added another route @app.route('/login') - the function under this decorator will be called when the visitor to our website goes to http://my.website.com/login.

Let's now move on to templates.


No comments:

Post a Comment