Creating a Basic Python Web App with Flask

Simple web applications in Python are easily constructed with the Flask micro-framework.

Why would you want a web app and not just a web page?

You can make quite sophisticated web pages with just HTML and Javascript but if you want to incorporate data that needs to be stored somewhere, or needs some sort of sophisticated processing, you might be better off building a proper application.

Traditionally, web applications were written in PHP, JSP or ASP. But these days Python is an perfectly good choice for creating web apps.

In this article we are going to make a simple example of a Python web app using Python and Flask.
Here's what we'll do:

1. Get the Flask library for Python and learn how to use it.
2. Write a Flask-based program to provide some simple data.
3. Write a web page template to display that data.

You don't need a high level of skill to follow this tutorial but you do need to have a basic knowledge of Python and HTML, and know what a web page and a server is. I also assume that you have Python installed on your computer (if not see this).

One more thing you need to know before we start is that we will use Python 3 in this tutorial. This is important as there are some differences between Python 2 and 3, which will mean that some things in the tutorial won't work if you use Python 2.

Getting Flask

We can get Flask simply by typing this is in a terminal window:

pip3 install flask

It shouldn't take too long and when it is complete Flask is installed and we are ready to begin in earnest.

Your first Flask program

You probably want to create a new folder for this tutorial so do that and open an editor (e.g. IDLE) to start creating your first program there. I will assume that it is called hello.py. We are going to make this very simple, just to see how Flask works. Type in the following program:

import flask

app = flask.Flask(__name__)

@app.route("/")
def hello():
 return  "Hello from Flask"


Before we can run it there is a couple of things we need to do.  Have you still got that terminal window open? Great.

Before we run our Flask program we need to set an environment variable that identifies the Python program that should be run. From the Windows command prompt you use the set command like this:

set FLASK_APP=hello.py

Or from Powershell, this:

$env:FLASK_APP = "hello.py"


And in Linux do this:

export FLASK_APP=hello.py

To run the flask program we will issue the command:

flask run 


We'll go through how it works shortly but first let's just run the program. The result you will get is this:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Now, open a web browser and, in the address bar, type

http://127.0.0.1:5000/

What you are doing here is loading the web page on your local server at port 5000. If that doesn't mean much to you, don't worry. In simple terms, the Flask program that you are running is a web server and the page that is displayed in the browser is what you have programmed it to be. You should have a browser window with the message "Hello from Flask".


How good is that!

Well, alright, it's not that exciting but we actually done quite a lot in this small piece of code.

Let's look at it a bit more closely.

The first line imports the Flask library - simple enough. The second line creates a Flask object called app and this is the thing that does all the work.

For the moment skip the line beginning with @.

The next couple of lines define a function called hello that returns a message.

So what does all that mean?

The command flask run starts a web server so when you open your browser, and give it the right address, a web page is displayed (it helpfully tells you what the address is). And the content of the web page is defined by the function hello.

But, hold on, what if we want lots of web pages and define them with different functions? How does the server know which one to send to the browser?

That's where the line
 
@app.route("/") 

comes in.

A line beginning with @ is called a decorator and it tells the Flask library that the function that follows is associated to the route "/". If that line had been

@app.route("/hello/")

Then the route would have been "/hello/" and you would have had to type

http://127.0.0.1:5000/hello

in the browser to to display the right page. You can try this if you like. 

Flask templates 

A one-line message is not much of a web page. You hopefully know that a simple web page looks something like this :

<head>
   <head>
      <title>Hello</title>
   </head> 
   <body>
      <h1>Hello from Flask</h1>
   </body>
</html>

It would be quite tedious to put all the html code in Python strings, so Flask provides templates. Flask templates are separate html files that contain the necessary code for a web page, plus some special code that lets Flask insert values into the html.

It's easier to understand with an example. And that's exactly what we will do in part 2 of this tutorial.

Flask templates


We've seen that we can generate a simple message from our Flask server but to build a more sophisticated web page we need to write some HTML and the simplest way to do this is with a template.

So let's dive in straight away with some code. Here is a slightly different version of out 'Hello' program:

import flask
from flask import render_template

app = flask.Flask(__name__)

@app.route("/")
def root():
 message = "Hello from Flask"
 return  render_template("hello.html", msg=message)



You can type it in but don't run it yet, you'll just get a server error instead of a web page.

So what's the difference between this and the first program? Notice that firstly, we have a new import from the Flask library. Also, we've assigned the message to be displayed to a variable called message. Next, the return statement has changed. Instead of simply returning the message we are calling the function render_template (from the library that we imported earlier). The first parameter for this function is the name of a web page (which we now have to write!) and the second one is passing the variable message to the web page and saying that within the web page it will be called msg.

Here is the template:

<!DOCTYPE html>

<html>
   <head>
      <title>A Flask template</title>
   </head>
   <body>
      <h1>{{msg}}</h1>
   </body>
</html>

as you can see it's pretty much a standard HTML file. There is one small difference, inside the <h1> tags the are a pair of double curly braces and inside these is msg, the name of variable that contains our message string. The double curly braces simply mean insert the value of the variable (or expression) within them.

To create this template we first need to create a folder called templates. This is important.  Flask expects templates to be in this folder. Next, with your favourite editor, create a file called hello.html inside that folder.

Now open your web browser, at the same address as before, and you'll see this:

Much the same as before but this time it's a proper web page and the message that we have passed into it is rendered as a heading.

So that's fine, we can serve a web page of our own design and insert things into it from our Python program.

Of course we will want to do more than this. The data that we send to our web page will probably come from a database or an outside source - we'll think about how we can develop from this in later articles.

In the mean time, thanks for reading and I hope that this has been helpful.

If you found this tutorial interesting, please share with your friends and please feel free to comment.



Just Enough Python
An brief introduction that will get you programming quickly

Comments

Popular posts from this blog

3 Excellent Python IDEs for beginners - Thonny, Geany or Idle

Simple Data Visualization Tools in Python and Pandas

Setting Up Jupyter Notebooks for Data Visualization with Anaconda