Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
MJRoBot (Marcelo Rovai)
Published © LGPL

Python WebServer With Flask and Raspberry Pi

Let's create a simple WebServer to control things in your home, using FLASK and Python to control Raspberry's GPIOs.

BeginnerFull instructions provided4 hours21,913
Python WebServer With Flask and Raspberry Pi

Things used in this project

Story

Read more

Schematics

electrical diagram

Code

Code snippet #7

Plain text
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello world'

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

Code snippet #15

Plain text
<!DOCTYPE html>
   <head>
      <title>{{ title }}</title>
   </head>

   <body>
      <h1>Hello, World!</h1>
      <h2>The date and time on the server is: {{ time }}</h2>
   </body>
</html>

Code snippet #16

Plain text
'''
Code created by Matt Richardson 
for details, visit:  http://mattrichardson.com/Raspberry-Pi-Flask/inde...
'''

from flask import Flask, render_template
import datetime
app = Flask(__name__)

@app.route("/")
def hello():
   now = datetime.datetime.now()
   timeString = now.strftime("%Y-%m-%d %H:%M")
   templateData = {
      'title' : 'HELLO!',
      'time': timeString
      }
   return render_template('index.html', **templateData)

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

Code snippet #19

Plain text
<!DOCTYPE html>
   <head>
      <title>{{ title }}</title>
      <link rel="stylesheet" href="../static/style.css/">
   </head>

   <body>
      <h1>Hello, World!</h1>
      <h2>The date and time on the server is: {{ time }}</h2>
   </body>
</html>

Code snippet #20

Plain text
'''
	Raspberry Pi GPIO Status and Control
'''
import RPi.GPIO as GPIO
from flask import Flask, render_template

app = Flask(__name__)

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

button = 20
senPIR = 16

buttonSts = GPIO.LOW
senPIRSts = GPIO.LOW
   
# Set button and PIR sensor pins as an input
GPIO.setup(button, GPIO.IN)   
GPIO.setup(senPIR, GPIO.IN)
	
@app.route("/")
def index():
	# Read Sensors Status
	buttonSts = GPIO.input(button)
	senPIRSts = GPIO.input(senPIR)

	templateData = {
      'title' : 'GPIO input Status!',
      'button'  : buttonSts,
      'senPIR'  : senPIRSts
      }
	return render_template('index.html', **templateData)

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

Code snippet #22

Plain text
<!DOCTYPE html>
   <head>
      <title>{{ title }}</title>
      <link rel="stylesheet" href='../static/style.css'/>
   </head>

   <body>
	  <h1>{{ title }}</h1>
      <h2>Button pressed:  {{ button }}</h1>
      <h2>Motion detected: {{ senPIR }}</h2>
   </body>
</html>

Code snippet #23

Plain text
'''
	Raspberry Pi GPIO Status and Control
'''
import RPi.GPIO as GPIO
from flask import Flask, render_template, request

app = Flask(__name__)

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

#define actuators GPIOs
ledRed = 13
ledYlw = 19
ledGrn = 26

#initialize GPIO status variables
ledRedSts = 0
ledYlwSts = 0
ledGrnSts = 0

# Define led pins as output
GPIO.setup(ledRed, GPIO.OUT)   
GPIO.setup(ledYlw, GPIO.OUT) 
GPIO.setup(ledGrn, GPIO.OUT) 

# turn leds OFF 
GPIO.output(ledRed, GPIO.LOW)
GPIO.output(ledYlw, GPIO.LOW)
GPIO.output(ledGrn, GPIO.LOW)
	
@app.route("/")
def index():
	# Read Sensors Status
	ledRedSts = GPIO.input(ledRed)
	ledYlwSts = GPIO.input(ledYlw)
	ledGrnSts = GPIO.input(ledGrn)

	templateData = {
              'title' : 'GPIO output Status!',
              'ledRed'  : ledRedSts,
              'ledYlw'  : ledYlwSts,
              'ledGrn'  : ledGrnSts,
        }
	return render_template('index.html', **templateData)
	
@app.route("/<deviceName>/<action>")
def action(deviceName, action):
	if deviceName == 'ledRed':
		actuator = ledRed
	if deviceName == 'ledYlw':
		actuator = ledYlw
	if deviceName == 'ledGrn':
		actuator = ledGrn
   
	if action == "on":
		GPIO.output(actuator, GPIO.HIGH)
	if action == "off":
		GPIO.output(actuator, GPIO.LOW)
		     
	ledRedSts = GPIO.input(ledRed)
	ledYlwSts = GPIO.input(ledYlw)
	ledGrnSts = GPIO.input(ledGrn)
   
	templateData = {
              'ledRed'  : ledRedSts,
              'ledYlw'  : ledYlwSts,
              'ledGrn'  : ledGrnSts,
	}
	return render_template('index.html', **templateData)

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

Code snippet #27

Plain text
<!DOCTYPE html>
   <head>
      <title>GPIO Control</title>
      <link rel="stylesheet" href='../static/style.css'/>
   </head>

   <body>
		<h1>Actuators</h1>
		<h2> Status </h2>
		<h3> RED LED ==>  {{ ledRed  }}</h3>
		<h3> YLW LED ==>  {{ ledYlw  }}</h3>
		<h3> GRN LED ==>  {{ ledGrn  }}</h3>
		<br>
		<h2> Commands </h2>
		<h3> 
			RED LED Ctrl ==> 
			<a href="/ledRed/on" class="button">TURN ON</a>  
			<a href="/ledRed/off"class="button">TURN OFF</a>
		</h3>
		<h3> 
			YLW LED Ctrl ==> 
			<a href="/ledYlw/on" class="button">TURN ON</a>  
			<a href="/ledYlw/off"class="button">TURN OFF</a>
		</h3>
		<h3> 
			GRN LED Ctrl ==> 
			<a href="/ledGrn/on" class="button">TURN ON</a>  
			<a href="/ledGrn/off"class="button">TURN OFF</a>
		</h3>
		
   </body>
</html>

Code snippet #28

Plain text
body {
	background: blue;
	color: yellow;
}

.button {
  font: bold 15px Arial;
  text-decoration: none;
  background-color: #EEEEEE;
  color: #333333;
  padding: 2px 6px 2px 6px;
  border-top: 1px solid #CCCCCC;
  border-right: 1px solid #333333;
  border-bottom: 1px solid #333333;
  border-left: 1px solid #CCCCCC;
}

Code snippet #29

Plain text
'''
	Raspberry Pi GPIO Status and Control
'''
import RPi.GPIO as GPIO
from flask import Flask, render_template, request

app = Flask(__name__)

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

#define sensors GPIOs
button = 20
senPIR = 16

#define actuators GPIOs
ledRed = 13
ledYlw = 19
ledGrn = 26

#initialize GPIO status variables
buttonSts = 0
senPIRSts = 0
ledRedSts = 0
ledYlwSts = 0
ledGrnSts = 0

# Define button and PIR sensor pins as an input
GPIO.setup(button, GPIO.IN)   
GPIO.setup(senPIR, GPIO.IN)

# Define led pins as output
GPIO.setup(ledRed, GPIO.OUT)   
GPIO.setup(ledYlw, GPIO.OUT) 
GPIO.setup(ledGrn, GPIO.OUT) 

# turn leds OFF 
GPIO.output(ledRed, GPIO.LOW)
GPIO.output(ledYlw, GPIO.LOW)
GPIO.output(ledGrn, GPIO.LOW)
	
@app.route("/")
def index():
	# Read GPIO Status
	buttonSts = GPIO.input(button)
	senPIRSts = GPIO.input(senPIR)
	ledRedSts = GPIO.input(ledRed)
	ledYlwSts = GPIO.input(ledYlw)
	ledGrnSts = GPIO.input(ledGrn)

	templateData = {
      		'button'  : buttonSts,
      		'senPIR'  : senPIRSts,
      		'ledRed'  : ledRedSts,
      		'ledYlw'  : ledYlwSts,
      		'ledGrn'  : ledGrnSts,
      	}
	return render_template('index.html', **templateData)
	
@app.route("/<deviceName>/<action>")
def action(deviceName, action):
	if deviceName == 'ledRed':
		actuator = ledRed
	if deviceName == 'ledYlw':
		actuator = ledYlw
	if deviceName == 'ledGrn':
		actuator = ledGrn
   
	if action == "on":
		GPIO.output(actuator, GPIO.HIGH)
	if action == "off":
		GPIO.output(actuator, GPIO.LOW)
		     
	buttonSts = GPIO.input(button)
	senPIRSts = GPIO.input(senPIR)
	ledRedSts = GPIO.input(ledRed)
	ledYlwSts = GPIO.input(ledYlw)
	ledGrnSts = GPIO.input(ledGrn)
   
	templateData = {
	 	'button'  : buttonSts,
      		'senPIR'  : senPIRSts,
      		'ledRed'  : ledRedSts,
      		'ledYlw'  : ledYlwSts,
      		'ledGrn'  : ledGrnSts,
	}
	return render_template('index.html', **templateData)

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

Code snippet #30

Plain text
<!DOCTYPE html>
   <head>
      <title>GPIO Control</title>
      <link rel="stylesheet" href='../static/master.css'/>
   </head>

   <body>
		<h1>RPi GPIO Control</h1>
		<h2> Sensor Status </h2>
		<h3> BUTTON ==>  {{ button  }}</h3>
		<h3> MOTION ==>  {{ senPIR  }}</h3>
		<br>
		
		<h2> Actuator Status </h2>
		<h3> RED LED ==>  {{ ledRed  }}</h3>
		<h3> YLW LED ==>  {{ ledYlw  }}</h3>
		<h3> GRN LED ==>  {{ ledGrn  }}</h3>
		<br>
		<h2> Commands </h2>
		<h3> 
			RED LED Ctrl ==> 
			<a href="/ledRed/on" class="button">TURN ON</a>  
			<a href="/ledRed/off"class="button">TURN OFF</a>
		</h3>
		<h3> 
			YLW LED Ctrl ==> 
			<a href="/ledYlw/on" class="button">TURN ON</a>  
			<a href="/ledYlw/off"class="button">TURN OFF</a>
		</h3>
		<h3> 
			GRN LED Ctrl ==> 
			<a href="/ledGrn/on" class="button">TURN ON</a>  
			<a href="/ledGrn/off"class="button">TURN OFF</a>
		</h3>
		
   </body>
</html>

Github

https://github.com/Mjrovai/RPi-Flask-WebServer

Credits

MJRoBot (Marcelo Rovai)

MJRoBot (Marcelo Rovai)

67 projects • 959 followers
Professor, Engineer, MBA, Master in Data Science. Writes about Electronics with a focus on Physical Computing, IoT, ML, TinyML and Robotics.

Comments