Skip to main content

Flask web pages (Lab 5e)

Flask is a small Python web framework: it turns Python functions into web pages. In Lab 5e it shows the MySensor table in the browser. The lab sheet has the code; this page explains how Flask works so you can fix and extend it.

Flask vs Apache​

Apache (+ PHP)Flask
Started bysystemd, at every bootYou, by running app.py
Port80 (http://localhost)5000 (http://localhost:5000)
Pages live in/var/www/htmlYour Python code + templates/
Stops whenYou stop the serviceYou press Stop, close Thonny, log out or reboot

They run side by side without conflict because they use different ports.

The three ideas​

  1. Routes connect a URL to a function:

    @app.route('/hello/<name>')
    def hello(name):
    return f'Hello {name}'

    http://localhost:5000/hello/Ali runs hello('Ali').

  2. Templates are HTML files in a templates folder with placeholders, filled in by render_template('page.html', message=..., results=...). The names you pass (results=) are the names the template uses.

  3. Jinja2 is the placeholder language inside templates:

    SyntaxDoes
    {{ message }}Prints a value
    {% for row in results %} ... {% endfor %}Repeats a block for each row
    {% if results %} ... {% else %} ... {% endif %}Shows one part or another
    {{ row[0] }}The first column of a row

How the Lab 5e page gets its data​

  1. The route connects with pymysql (same login as Lab 5d).
  2. cursor.fetchall() returns a list of rows. Each row is a tuple in column order: row[0] SerialNo, row[1] SensorID, row[2] Temp, row[3] Dist, row[4] SensorDate.
  3. The rows go to the template, which loops over them to build the HTML table.

Where the query runs matters. If it runs once when app.py starts (outside the route function), the page shows the same old rows until you restart app.py. Put the connect + query inside the route function and every refresh shows the newest data.

Useful changes to try:

  • Newest first, only 20 rows: SELECT * FROM Data ORDER BY SerialNo DESC LIMIT 20
  • Refresh the page by itself every 5 seconds: add <meta http-equiv="refresh" content="5"> inside <head>.
  • Round the temperature in the template: {{ "%.1f"|format(row[2]) }}

Folders​

/home/pi/
├── app.py
├── templates/ <- HTML files (exact name, lower case)
│ └── sql-data.html
└── static/ <- CSS, images
└── style.css

Flask finds templates and static next to app.py (or where template_folder= points). In a template, link CSS with {{ url_for('static', filename='style.css') }}.

Debug mode​

While developing, start Flask with:

app.run(debug=True)

Now errors are shown in the browser with the exact line, and Flask restarts itself when you save app.py. Turn it off (debug=False) before letting other people use the page: the debug page lets anyone who sees it run Python on your Pi.

Opening the page from a laptop or phone​

By default Flask only answers the Pi itself (127.0.0.1). To allow other devices on the network:

app.run(host='0.0.0.0', port=5000)

Then browse to http://<Pi IP>:5000 (find the IP with hostname -I). Check what Flask is listening on with sudo ss -tlnp | grep 5000.

Common problems​

ProblemFix
This site can't be reachedapp.py is not running, or :5000 is missing from the URL.
Works on the Pi, not from the laptopAdd host='0.0.0.0'; use the Pi's IP, not localhost; same network?
Address already in use / Port 5000 is in use by another programAn old Flask is still running. Stop it in Thonny, or sudo fuser -k 5000/tcp.
jinja2.exceptions.TemplateNotFound: sql-data.htmlWrong folder (Templates ≠ templates), wrong file name, or wrong template_folder.
jinja2.exceptions.UndefinedError / blank valuesThe name in the template does not match the name passed to render_template.
Table shows old dataThe query runs outside the route. Move it inside.
CSS not appliedstatic/style.css missing, <link> wrong, or the browser cached it: Ctrl+Shift+R.
Internal Server ErrorLook in Thonny's shell for the Python traceback, or use debug=True.
ModuleNotFoundError: No module named 'flask'Wrong interpreter: venv and Thonny.
pymysql.err.OperationalError (1045 ...)Database login problem: MariaDB users.
Page stops after closing SSH or ThonnyFlask runs only while app.py runs. Start it again (run it as a service).

The "This is a development server. Do not use it in a production deployment" warning is normal for labs.