Running Flask as a server#

We will show you how to set up and run a Flask based server

Requirements

  1. PC or Raspberry Pi

  2. Python

Guide#

The first step is to install Flask make sure you have python correctly installed. We advise you to use a python enviroment manager such as conda

Verify Python installation#

python --version

Upgrade with pip

python -m ensurepip --upgrade

Install Flask with pip

pip install Flask

Install Flask with conda

conda install flask

Create your server file#

Now Flask is installed we need to create a server file which defines the settings of the Flask server

from flask import Flask, request, render_template

app = Flask(__name__)

# Variables to store temperature and humidity values
temperature = None
humidity = None

@app.route('/dht-server', methods=['GET', 'POST'])
def handle_request():
    global temperature, humidity
    
    if request.method == 'POST':
        temperature = request.form.get('temperature')
        humidity = request.form.get('humidity')
        print("Received Temperature:", temperature)
        print("Received Humidity:", humidity)
        return "Data received successfully"
    elif request.method == 'GET':
        return render_template('index.html', temperature=temperature, humidity=humidity)

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

In this example the Flask server runs and can either process a POST or a GET request.

If a GET request is made the current temperature and humidity are returned

If a POST request is made then the temperature and humidity are set from the post request.

Warning

In this example we set up the server in debugging mode with external availablity.

This can be insecure, so follow the guidance that Flask provide on securing the server

Run the server from Command prompt#

cd to the directory containing server.py.

Start the server in cmd:

python server.py

Locate the server’s ip address#

Find Server IP Address:

Look for the IP address the server is running on:

* Running on all addresses (0.0.0.0)
* Running on http://IPaddress:80
* Running on http://IPaddress:80

Verify the serve is running#

From Commmand Prompt type:

curl http://IPAddress:Port

For example:

curl http://192.43.0.1:5000

You can verify with the server logs:

192.43.0.1 - - [Date Time] "GET / HTTP/1.1" 200 -