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

import json

from flask import Flask, request

app = Flask(__name__)


@app.route("/datalog", methods=["POST"])
def handle_post():
    request_data = request.get_json()
    # Code can be added here to save the json data into a log - either file or SQL
    return f"Recieved the following data:\n { json.dumps(request_data, indent=10)}"


if __name__ == "__main__":
    app.run(debug=True, port=5000)

In this example the Flask server runs and can only process a POST request.

If a POST request is made then the JSON formatted data can be logged by the server.

In reponse the server lets the sender know what it recieved

Warning

In this example we set up the server in debugging mode. Any running server can pose a security risk.

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 -