Passing Parameters to an HTML Page from a Raspberry Pi Web Server


Description

This project builds on the previous project in which we created a basic web server. In this project I’ll show you how to collect some basic information about your Pi and web server, and then pass that information as parameters to an HTML page that we’ll create so it can be displayed in a browser.

Parameters

This is some information about this project and the conditions under which it was done. If you try to replicate it in the future and it doesn’t work, you can evaluate these parameters to see if any changes between these and your configuration might have impacted your results. An example might be changes to future versions of Python or Flask.

  • Date: July 16, 2021
  • Skill: Beginner
  • Raspberry Pi Model(s): Zero-W, 3B+, 4B
  • OS: Raspberry Pi OS version 10 (Buster)
  • Python Version: 3.7.3
  • Flask Version: 1.0.2

Steps

  1. Let’s start by opening up our web server app (/home/pi/sample/sample.py) in GeanyThonny or your favorite Python editor.
  1. Now add the follow changes to your code:
from flask import Flask, render_template
from datetime import datetime
import io
import os

START_DATE = datetime.now().strftime('%m/%d/%y %I:%M:%S %p')

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/healthcheck')
def healthcheck():
    curDateTime = datetime.now().strftime('%m/%d/%y %-I:%M:%S %p')

    # Report available disk space
    stat = os.statvfs('/home/pi')
    gbFree = '%0.2f GB' % (stat.f_bfree*stat.f_bsize/1024/1024/1024)

    # Report CPU Temp
    try:
        tFile = open('/sys/class/thermal/thermal_zone0/temp')
        temp = float(tFile.read())
        tempC = '%0.1f C' % (temp/1000)
        tempF = '%0.1f F' % ((temp/1000) * 1.8 + 32)
    except:
        tempC = 'ERR'
        tempF = 'ERR'

    tFile.close()

    return render_template('health.html', curDate=curDateTime, startDate=START_DATE, gbFree=gbFree, tempC=tempC, tempF=tempF)

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

You’ll notice we added a new healthcheck route and we captured the date/time that the server started so we can show that as part of our healthcheck. This will help us keep track of how long the server has been up, along with the current date/time, which will just validate that the clock on the pi is accurate (which it should be as long as it’s connected to the internet). We also added some OS calls to get available disk space and cpu temperature. Nothing too fancy, but good basic stuff to know. You can add more data elements over time to capture anything else you find useful.

  1. Save the changes to sample.py and run the server if it didn’t auto-restart.
  1. Now lets create the health.html file. Create a new file in Geany or your favorite editor. Enter the following lines:
<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='utf-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <title>Healthcheck</title>

  <style>
    body {
      font-size: 28px;
      background-color: lightblue;
    }
    table, th, td {
      border: 1px solid black;
      border-collapse: collapse;
      padding: 15px;
    }
    th {
      text-align: right;
      background-color: skyblue;
    }
    td {
      background-color: white;
    }
  </style>

</head>

<body>
  <h2>Health Check</h2>
  
  <table>
    <tr>
      <th>Health Status as of:</th>
      <td><b>{{curDate}}</b></td>
    </tr>
    <tr>
      <th>Running Since:</th>
      <td><b>{{startDate}}</b></td>
    </tr>
    <tr>
      <th>Available Disk Space:</th>
      <td><b>{{gbFree}}</b></td>
    </tr>
    <tr>
      <th>CPU Temperature:</th>
      <td><b>{{tempF}} ({{tempC}})</b></td>
    </tr>
  </table>
  <p><a href='/'>Index</a></p>
</body>

</html>

Save the file to: /home/pi/sample/templates/health.html

I won’t explain all of the HTML and CSS elements above, but the important piece I’m trying to demonstrate is the ability to pass parameters into your HTML. You can see that I put the names of the parameters being passed inside of double-braces {{ }} inside of the elements that I want them to display. This has been a pretty handy trick! The last element inside the body is a link back to the index route in your server.

  1. Now you can modify index.html to include a link to the new healthcheck path. Enter the follow changes to the index.html file and save it:
<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      background-color: lightblue;
      color: blue;
    }
  </style>
</head>

<body>
    <h1>My Webserver!</h1>
    <p><a href='/healthcheck'>Health Check</a></p>
</body>
</html>

As you add additional routes to your server, you can add links to them here for easy access.

Enter the address of your server in a browser (i.e., http://192.168.2.221:5000/) and you should see a new Health Check link.

Click it and it should take you to your new Health Check page, with all of the data you passed from your server.

If you click the Index link, it will take you back to your index/home page.

Summary

In this project we built upon our Basic Raspberry Pi Web Server to add an additional route and passed dynamic data elements as parameters to our HTML file. This is a useful feature that I’m sure you’ll use again as you create your own server projects.

In the next project, we’ll add the ability to shutdown and reboot your Pi through new routes. This can be helpful if your Pi is running ‘headless’ (i.e., no attached monitor, keyboard or mouse).

Learn More

Raspberry Pi / Raspberry Pi OS

Python / HTML / CSS

Flask

1 thought on “Passing Parameters to an HTML Page from a Raspberry Pi Web Server”

Leave a Comment

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