Advertisement

Thursday, 10 March 2016

Use Flask to put your Pi data on the net - part 1


The Raspberry Pi is a brilliant piece of kit for interfacing with the real world and it is also a fully fledged computer that can run a web server and communicate with the rest of the world via the Web.

Most web applications are written in PHP, Java, Ruby or one of Microsoft's languages like C# and use a web server such as Apache or IIS. Flask let's you do the same thing with Python.

So, what we're going to do is write a simple Python/Flask program to combine the best of these two worlds and publish data read by the Pi to your network, where you can view it on your laptop or phone. 

What are going to make is a simple example of the use of Flask and Python that could be the basis of a remote monitoring or remote control system. We won't be going that far in this tutorial because our main aim here is to introduce Flask. But, so as to make it a real project we are going to put images from a camera (pi cam or usb camera) on your local network.

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 read a camera image, and it's description, from the Pi.
3. Write a web page template to display that data.

I'm making certain assumptions here. They are:

1. You have set up your Pi with the Raspbian operating system and it is connected to your home network.
2. You are reasonably familiar with Raspbian and you have, at least, experimented with programming in Python.

You don't need a high level of skill to follow this tutorial but you do need to have played around with your Pi and with Python.

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

Getting the Pip

In order to get Flask, we first of all have to make sure that we have pip, the Python package installer. It's probably there already; to check open a terminal window and type pip3 into it. If it responds with a whole load of help text, then you've already got it, otherwise use apt-get to get it. Type this in the terminal:

sudo apt-get install python3-pip

When that's all done we can get Flask simply by typing this is the terminal:

sudo pip3 install flask

This may take a little while but when it is complete Flask is installed and we are ready to begin in earnest.

Your first Flask program

Let's be organised about this and create a new folder for this tutorial. Either use the file manager to do this or type mkdir newdirectoryname in the terminal. Now cd to the new directory and create a new Python file called main.py (touch main.py). Now open an editor, or use IDLE, to start creating your first program. 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"

if __name__ == "__main__":
 app.run()

We'll go through how it works shortly, but first, save the program and run it (either from IDLE or by typing python3 main.py in a terminal window). 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, for the address, 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. 

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. And the last couple of lines calls the run function, from the app object, when the program is run.

So what does all that mean?

The app.run() function 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 html 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.

If you found this post interesting, please share it with your friends.

Find out more about Flask.

No comments:

Post a Comment