How to make a web interface for Raspberry Pi with Flask

Here’s an example of how to build a python based web server usingflask library to control a LED via form button. Do take a look at  my music server post for an application – I used a similar webapp to control functions as reboot , shutdown for my music server.The following guide is written assuming the reader has a basic understanding of Html, Raspberry Pi and python scripting.

 

So why web- based? 

The main advantages of using a web browser based solution over a purpose built app is that there is no client installation and any device on your network can use it. This makes it ideal if you change your phone / tablet often because you’re not dictated by the operating system support or manufacturers. For more complex projects a purpose made app may be a better solution but for controlling a few functions a webapp seems ideal.

Install Flask

You need to install pip python if you haven’t:

sudo apt-get install python-pip

… put kettle on

Install flask now:

sudo pip install flask

Knowing your ip address

First identify your ip address of your raspberry pi as it will be required later.

  • Few ways of doing this are:
    On raspbian the ip address is normally displayed before the login prompt.
  •  Type

ifconfig

cmd and this will display the ip address

Basic flask working example

Create a new file and put the following below in and save it as flask_hello.py etc

from flask import Flask 

app = Flask(__name__)

@app.route("/")

def hello():
	return "Hello World!"

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

Run the file

sudo python flask_hello.py

Type into a webrowser on you network

http//:your rpi ip address:5000

If all goes well you should have a page with ‘hello world’ on it

 

Jquery Mobile Form  drive Led example

Web server project folder structure
Now we have tested our basic server and everything is working we can use a web form to control a led.

First make the project folder structure

cd /home/pi/

sudo mkdir web_control

Inside this web_control folder, make the following folder:

Templates directory houses all html files.

cd web_control

sudo mkdir templates

So when done the folder should look like this:

/web_control/
——-/templates

Python script
Create a new file called my_webserver.py and put the following below in and save it the web_control folder created earlier: /home/pi/web_control/.

#raspberry pi flask webserver Jquery mobile form example by ls-homeprojects.co.uk
#Use this how you wish but please keep this header if re-posted



from flask import Flask, render_template , request

import RPi.GPIO as GPIO


led_pin = 26       			    #led connected to gpio 26 change to your own choice
GPIO.setmode(GPIO.BCM)   		#gpio numbering 
GPIO.setup(led_pin , GPIO.OUT)  #Set led pin as output




app = Flask(__name__)

@app.route("/")                 



   


   
 
@app.route("/", methods=['POST'])  

def mymenu():  
	if request.method == 'POST':  
        # Get the value from the submitted form  
		submitted_value = request.form['myform']  
		
		if submitted_value =="Led_on":   #if form submits "myform=Led_on" then turn led on !
			GPIO.output(led_pin, True)		
			
		if submitted_value =="Led_off":   #if form submits "myform=Led_off" then turn led off !
			GPIO.output(led_pin, False)
		
		if submitted_value =="Reboot":   #if form submits "myform=reboot" then..
			print "Add your code in for reboot ect here... "
		
		
		
		print "Button value :   ", submitted_value  
       

	return render_template('form_test.html') #Load our html file from template dir
   
   
  
   
     
if __name__ == "__main__":
   app.run(host='0.0.0.0', port=5000, debug=False)       #Run flask app !
   


 

Html form
Make a new file and put the following below into it saving as ‘form_test.html’  in the templates directory created earlier:  /home/pi/web_control/templates.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

</head>

<body>

<div data-role="page" >
  <div data-role="main" class="ui-content">
    <form method="post" action="/">
      
	    <h3><strong>www.ls_homeprojects.co.uk flask example</strong></h3>

		
		
      <button name="myform" align="left" data-inline="true" value="Button_1"> button 1</button>
      <button name="myform" align="left" data-inline="true" value="Button_2"> button 2 </button>
	  
	  
	   <h3><strong>Led Control example</strong></h3>
	   <button name="myform" align="left" data-inline="true" value="Led_on"> LED ON</button>
      <button name="myform" align="left" data-inline="true" value="Led_off"> LED OFF </button>
	  
	  
	    <h3><strong>Reboot example</strong></h3>
	   <button name="myform" align="left" data-inline="true" value="Reboot"> Reboot Server !</button>
	  
	  
	  
	  
	  
	      
     
    </form>
  </div>
</div>

</body>
</html>

JQuery mobile ?
JQuery mobile is a framework that basically transforms a web page into a mobile web app and is ideal for use on touch screen devices and also works fine on desktops. This is not required for the operation of this web server but gives a real nice web app feel when using on a tablet or mobile device.

For more information please look on the J Query Mobile website or  http://www.w3schools.com  . As the jquery framework is hosted online you will require a internet connection on the network that you are using for the j query framework to load please look at the first few lines of the HTML file for an example of this.

Run it !

cd /home/pi/web_control

sudo python my_webserver.py

Type into a webrowser on you network

http//:your rpi ip address:5000

How it works?
Html (webpage) :
Basically when a button is pressed it does form submit value for the myform variable such as button1, reboot ect.

(Python script):
Flask python looks for a form submit (post) request then finds the value for the “myform” variable.
Now we can use an “if statement” to determine the value of myform so then we can then do functions based on its value.

Hope this guide helps. Please feel free to use my examples how you wish but if re-posting elsewhere but please make reference to my work at: ls-homeprojects.co.uk.

Any questions please leave in the comments.

COMMENTS

Jonathan

Excellent intro. This has got me up and running in just a few minutes. Thanks Luke.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.