EBC Exercise 32 gpio via flask

From eLinux.org
Revision as of 08:19, 16 September 2020 by Yoder (talk | contribs) (Adding a template)
Jump to: navigation, search

thumb‎ Embedded Linux Class by Mark A. Yoder


Intro. Much of this is from https://towardsdatascience.com/python-webserver-with-flask-and-raspberry-pi-398423cc6f5d.

Installing Flask

Flask should already be installed on the Bone. But if not:

bone$ sudo apt update
bone$ sudo apt install python3-flask

All the examples are in the class repo

bone$ git clone https://github.com/MarkAYoder/BeagleBoard-exercises.git examples
bone$ cd examples/flash/server

First Flask - hello, world

Our first example is helloWorld.py

#!/usr/bin/env python3
# From: https://towardsdatascience.com/python-webserver-with-flask-and-raspberry-pi-398423cc6f5d

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
    return 'hello, world'
if __name__ == '__main__':
    app.run(debug=True, port=8081, host='0.0.0.0')

The first line loads the Flask module into your Python script. The second line creates a Flask object called app. The third line is where the action is, it says to run the index() function when someone accesses the root URL (‘/’) of the server. In this case, only send the text “hello, world” to the client’s web browser via return.

The last line says to “listen” on port 8081, reporting any errors.

Now on your host computer, browse to 192.168.7.2:8081 an you should see.

HelloFlask.jpg

Adding a template

Let’s improve our “hello, world” application, creating an HTML template and a CSS file for styling our page.

Templates

Create an HTML file that will be located in the “template” sub-folder, we can use separate files with placeholders for spots where you want dynamic data to be inserted. So, we will create a file named index1.html, that will be saved on /templates.

OK, let’s create templates/index1.html:

Index1.jpg

(Sorry about using an image here, it kept formatting the HTML tags. Go to the git repo to get the code.)

Observe that anything in double curly braces within the HTML template is interpreted as a variable that would be passed to it from the Python script via the render_template function. Now, let’s create a new Python script. We will name it app1.py:

# 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('index1.html', **templateData)
if __name__ == "__main__":
   app.run(host='0.0.0.0', port=80, debug=True)

Note that we create a formatted string("timeString") using the date and time from the "now" object, that has the current time stored on it. Next important thing on the above code, is that we created a dictionary of variables (a set of keys, such as the title that is associated with values, such as HELLO!) to pass into the template. On “return”, we will return the index.html template to the web browser using the variables in the templateData dictionary.

Execute the Python script:

bone$ .\app1.py

Open any web browser and browse to 192.168.7.2:8081. You should see:




thumb‎ Embedded Linux Class by Mark A. Yoder