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.


Friday, September 16, 2022

Flask Tutorial for beginners - Part 5

At this point you are ready to start the webserver and make sure your application is working. From the command line run the app.py file.

python app.py

You'll see output that looks like the following.


Note a couple of warnings regarding the fact that this is a development server.

Note the command I used to run the application.

Now using your web browser, go to the link specified. In the example above, it's 

http://127.0.0.1:5000

There's another way to run the application. Stop the current process using the CTRL+c keystroke. Now start the application again by typing:

flask run

You'll see something like the following.


The information here is similar, except for a couple of things. Firstly, the port number has changed, also, you can see two addresses to get to the application. This is because I have set a couple of environment variables before typing in flask run.

To set the environment variables on Linux/Mac, I typed:

export FLASK_DEBUG=1
export FLASK_APP=app.py
export FLASK_RUN_HOST=0.0.0.0
export FLASK_RUN_PORT=8080

The first export (DEBUG) runs the application in debug mode. This means that errors in the application will be displayed, not just on the console, but also in the web browser. This setting should not be enabled on a production server since users will also be able to see details on all errors.

The second export (APP) tells the command (flask run) which flask module to run.

The third export (RUN_HOST) indicates that the application should be accessible on all available addresses. This is useful if you need to access the application from a machine different from your development machine.

Last export (RUN_PORT) specifies the port that the application should listen to. You won't see this port on regular web requests since most browsers know that http is port 80 and https is port 443.

EXERCISES

You can now run a simple response application. Make the following changes to the application.

  1. Change the response string - instead of Hello World! return something like "Thanks for visiting"
  2. In your response, make one of the words bold (use HTML).
  3. In your response send a HTML link to a website so that when the user clicks on it, they are redirected to that page.
Can you find out how to make the environment variables permanent on your system?










Flask Tutorial for beginners - Part 4

Now that Flask is installed, let's write our first application. This will be a very simple application that returns the famous programming statement - Hello World!

WEBSERVER

One of the great things about developing using Python and Flask is that you get a free development web server while you are developing your application. We will use this to test our application.

A small note on additional tools. I've left out a discussion on what tools you can use to write code. I use Visual Studio Code - the free version - to do most of my work. This code editor is extremely powerful, popular and works on most operating systems. It is definitely available on Windows, Mac and Linux.

However, for most of the work we'll be doing, you can use Notepad on Windows, and any text editor on Mac or Linux. Python comes with a free code editor called Idle. I found this tutorial at Idle at RealPython to be the most informative. But a quick Google search for Python Idle and you will find a ton of resources.

COMMAND PROMPT

Open a command prompt and create a folder for your work. Then inside that folder, create a text file. I normally name my main Python/Flask application file app.py.

Open app.py and type in the following code - we'll discuss it line by line.


Line Number Description
1 This is the import line that imports the flask module into our application.
3 This creates a Flask object. You'll need exactly one of these in your application. This Flask object handles all the requests from the user on the other side of the Internet.
5 & 6 Line 5 is syntax you may not be used to. This is called a decorator. It's job is to add some special features to the function defined right after it. In this example, the decorator says that the route specified by the backslash should be handled by this function. The Python function (created using the def keyword) can be called anything. In our example, we've called it index. In our web application, this means that the user will go to my.website.com/  -   note the trailing slash.

Line 6 is the definition of the actual function that processes the request from the user. In this case, it's only one line, that returns a string - "Hello World!"
10 - 11 These are our typical Python execution lines. If you haven't seen them before, they execute if the module (in this case app.py) is called directly from the command line - but not execute if called from a different module.

That's it. We have some working code, hopefully no syntax error bugs.

Next step is to start the webserver which will run our application and then using a web browser we will test the code.

LOCAL TESTING

As you develop your application, you'll use the special address for your local computer - 127.0.0.1 (or localhost). The Python/Flask environment will make sure that the correct settings (such as opening a port for your browser) are configured.

Let's see how that works in the next tutorial.







Flask Tutorial for beginners - Part 3

INSTALLING PYTHON/FLASK

For Windows users, you can get a copy of Python at Python's official website at Python's Official Website

For most other operating systems (Mac and Linux), Python comes pre-installed though you may need to get an upgrade without removing the existing installed version.

But getting and installing Python is not in scope for this tutorial, we'll start with installing Flask.

To install Flask, the best option is to open a command prompt (or terminal) and type in the following command:

pip install flask

That's all

To check if flask is installed, in the same command prompt, launch python and type in the following at the Python prompt:

from flask import Flask

You should see output similar to the diagram below.


In the diagram above you note that the version of flask installed on my machine is version 3.7.3 and the computer is running Linux.

When I typed in from flask import Flask. Note that the Python prompt returns without any error messages.

If you see any error messages it means that Flask is not installed and you can try and run the pip command again. Please note that on some systems, you may have to switch your account to an administrator account in order to install Flask.

PYTHON/FLASK ONLINE

If you don't want to install Python/Flask on your computer, there are excellent resources online. One of the best is Pythonanywhere. You can sign up for a free account which is more than enough for the examples we will be working through.

Now that Flask is installed, let's write our first Python/Flask application. 










Flask Tutorial for beginners - Part 2

WHAT IS FLASK?

Flask is a framework for building web applications using the Python programming language.

A framework makes the work of writing a program easier by providing various building blocks so that you do not have to write a lot of code. For example, most frameworks handle the work of passing requests from the user (at the browser) back to the server.

Flask is considered a lightweight framework not as complete as some other frameworks, for example Django. In Flask, much of the setup work is still left to the programmer and there is a lot of flexibility in case you need to do something that the framework does not provide. In the case of Django, for example, you get a fully functional web application without writing a single line of code. With Flask, however, you need to write a few lines of code to get a simple web page to show.

Because Flask allows you to study closely how the interaction between a browser (your user) and the server (where the data and application lives) works, I think it's a very good place for us to learn how to write web applications.

Here's a rough diagram illustrating the relationship between the user, Python and Flask.



  • The user requests something from the Internet by typing in an address in their browser. 
  • This request reaches your application on the server and Flask answers it by looking at the address.
  • Flask then processes the request by passing it to a function in your Python application.
  • Once your function has completed processing the request, it hand it back to Flask to return the answer to the user.
Here's what a typical request might look like:

The user types in: https://my.website.com/login

The user has requested your website (my.website.com) and path is /login.

In the rest of this tutorial, we'll learn how to manage the path (/login) where we will present the user with a login page for them to type in their username (email) and a password.



At the top-left, the user asks for my.website.com. The request goes through the user's browser to the Internet to the website. Once there, Flask and Python take over to fetch the /login data. Flask then sends that back to the user.

In the next few sections, let's see how that's done.





Friday, August 5, 2022

Flask Tutorial for beginners - Part 1

It's about time I wrote about Python Flask. One of the easiest, most accessible Python frameworks for building software.

Python was originally thought of as a great scripting tool, but there are many examples of great commercial tools built using Python.

Learning Flask opens up a brand new way to automate business processes by building a web interface to your Python business logic.

Huge companies may have significant budgets to buy and customize software for millions of dollars. However, small and medium size businesses can use programming tools to build custom software for almost no cost.

This is probably why Microsoft built VBA (Visual Basic for Applications) into their Microsoft Office suite. And many companies have taken advantage of VBA's excellent programming interface to automate calculations in Excel, or even large documents.

This is what we're going to do:

  1. Talk about what Flask is and what it isn't.
  2. Install Flask (we'll be using a Linux machine (actually a Raspberry Pi) and also a Mac, but Windows will work also.
  3. Run a simple Flask program.
  4. Create a database program using Flask. Here we learn about getting input, cleaning it and then storing it. We'll use a lightweight database (sqlite) for this - so we may branch off and discuss sqlite.
  5. Introduce you to Bootstrap so that we can use some libraries to make the user interface beautiful (and responsive).
With this brief introduction, you should be able to build complex applications since you'll be able to create menu systems, text boxes to accept input, display data from databases and allow users to edit it.

Remember, a building of a hundred storeys begins with a single brick.

Let's get started on that brick.

Friday, April 22, 2022

File processing

Most programming languages have built-in facilities for opening and processing files. In this next set of posts, I'll highlight Python's simple file input/output methods for handling text files.

Most of these facilities can be used for processing input from a variety of sources, such as reading from a URL. And we will do that at the end of this set of posts. For now, let's just get started with a simple set of exercises.

We'll be using the following file:


It's a plain text file, so it can be read by almost all programs that read files. This particular file has 14 lines. Using the VI editor, you can get a line count by typing the following

:set number

or

:set nu

Make sure that you're not in INSERT mode (i.e., the word INSERT does not appear at the bottom left corner of the editor window).

Now onto programming.

Our file is named test.txt. In python, we assign a file variable using the open() function. We will then use this file variable to manipulate the contents of the file, such as reading or writing to the file.

Start your python editor and type in the following. Make sure that you are in the same folder that your file is located.


The file is opened using the following code:

f = open('test.txt', 'r')

f is the file handle, or variable, that we will use to manipulate the file contents.

open() is the function used to open the file. open() takes two arguments, the first is the name of the file you want to open, test.txt. The second is the mode in which you want to open the file. The mode can be:

r = read only
w = read and write (the file is created, if it exists, it's truncated)
a = append (the file is created if it does not exist)

Now that we've opened the file, let's read the first line and display it's contents.















We used the readline() function to read from the file handle f.

We put the contents returned by readline() into the variable line.

Then we used the print() function to display the contents of the variable line.

Note the format for reading from the file into the variable.

line = f.readline()

Now let's read the next line and display it's contents.


















We call readline() again to read the next line.

We use the same variable line to put the contents of the next line.
tabs
Python automatically moved to the next line after we read the first one.

Now let's go to the beginning of the file and use a for loop to read all the lines and display them.


































To go to the start of the file, we use the seek() function. The argument to the seek() function is the position in the file that we want to go to. In our case, we use the argument 0. Which means, to the beginning of the file.

Notice that the file seems bigger than the one we have. This is because the print() function automatically adds a newline after it writes the line to the screen. But each line also has a newline character at the end. So the file looks like it's double-spaced.tabs

We can remove the newline character from the line before we print it to the screen like this.





















The line that removes the newline character from the file is:

line = line.strip()

What this does is remove leading and trailing whitespace. A newline character, or spaces, or tabs at the front or end of the line would be stripped.

Now let's close the file and do some writing exercises.





To open a file for writing, which will also create the file, do the following:




If the file writing-file.txt existed, then python will truncate it. So be careful not to use the name of a file that you already have. For example, if we had used the name test.txt, our file that we used for the reading exercise would have been deleted.

Now let's write a few lines into the new file.






We've written four lines into our new file. Now let's read them.










Wow! What happened? The error message indicates that the file was not opened for us to read. There's a way to open a file for both reading and writing, but the mode we used 'w' was for writing only.

Let's close the file and open it for both reading and writing.


Dictionaries

Python has a dictionary data type.

The dictionary data type stores items as KEY: VALUE pairs. Unlike a list that stores items by their position in the array:

a[0], a[1], a[2], a[3]... 

A dictionary has no concept of order. The programmer determines what the key is, and assigns a value to it.

Consider the following list:












We create an empty list:

l = list()

We then append elements to the list. Recall that the list is ordered from zero.

for x in range(10):
    l.append(x)

The range() function returns a list of integers. In our example, range(10) will return the list:
[0,1,2,3,4,5,6,7,8,9]

Now let's remove the third element (l[2] - since the list is ordered from zero).








Notice how the item at position 2 has gone.

Actually the pop(x) method removes the element which has the value x. In the example above, if there was no "2" in the list, then an error would have been returned. The way to remove the 2-nd element is to use the del method.








In the example above, the element with value "3" is in the index position [2].

The statement:

del l[2]

deletes the "3"

[0, 1, 3, 4, 5, 6, 7, 8, 9]

becomes

[0, 1, 4, 5, 6, 7, 8, 9]

Now let's insert the "3" and the "2" back.









The insert(Pos, Value) function takes two arguments. Pos = the position (zero-based) where we will insert the element, and Value = the value of the element that we're inserting.

And now for the "2"








The function call, l.insert(2,2) will insert the value = 2 as position = 2.

DICTIONARIES are different. They are not based on indexed positions. Each entry in a dictionary has a key that marks where it is. The value is the actual element.

We can create an empty dictionary the following way:







Just like the list() function creates an empty list, the dict() function creates an empty dictionary. We can also create an empty list the following way:

l = []

And we can create an empty dictionary the following way:

d = {}

A dictionary uses curly braces (also known as brackets) to indicate that it's a dictionary.

Now let's add some elements to our empty dictionary. Remember, we need to add a key and an element. Unlike a list that only requires that you specify the element that you want to insert or append. A dictionary has no concept of ordering. We will see later how to sort dictionaries.










Notice a couple of things:

  • The key can be anything. A string or a number.
  • The value can be anything. A string or a number.
  • The key does not have to be related to the value.
A dictionary has an update() method if you want to add more than one key:value pair at once.

Let's see how this works:










Note the statement:

d.update({4: 'four', 5: 'five', 'holiday': 'Kwanzaa', 'lunari': 'X'})

This adds four elements. The keys are:

  • 4
  • 5
  • holiday
  • lunari
The values of each of those keys are:
  • four
  • five
  • Kwanzaa
  • X
It's probably best practice to use the update() method for all inserts so that you get used to it for single or multiple inserts.

Since dictionaries are unordered, to get a list of all the keys, the dictionary provides a keys() method.

This is how it works:





And the dictionary object also has a values() method that retrieves all the values. It works like this:




The keys() method is typically used in a loop to print out all the values. Like this:












The loop iterates through the list. The list is a list of keys. And inside the loop, the following statement runs:

print(key, ': ', d[key])

The print() statement will print a comma-separated list of items and add a newline at the end.