#Python – Flask Webserver sharing information from values in a different thread

Buy Me A Coffee

Hi !

I have a common scenario which involves:

  • A sensor collecting information
  • A web-server publishing the sensor information

This is simple, however the sensor does not support constants requests, and it may return a “too many requests” response when called directly. The idea to get the sensor information directly in the web-request was not valid from day zero.

I asked for support / guidance and my amazing and smart friends show me the concept of OVER ENGINEERING. Dockers, Compose, Queues, Coordination and more was part of some of the proposals. However, they also show me the most easy and simple way to solve this: Multi-threading.

  • Thread 1, where an infinite loop request information from the sensor, and stores the latest value to be shared.
  • Thread 2, where a web-server process requests and share the latest sensor information.

Easy ! And after a couple of tests, I manage to create a single file implementing this:

# Bruno Capuano
# start a webserver with flask in a thread
# start a different thread +1 a shared var
from flask import Flask
import threading
import time
iCounter = 0
data = 'foo'
app = Flask(__name__)
def mainSum():
# increment counter every second
global iCounter
while True:
iCounter = iCounter + 1
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print(str(f"{current_time} – data {iCounter}"))
time.sleep(1)
def startWebServer():
app.run(host='0.0.0.0', port=8080)
@app.route("/getdata")
def main():
global iCounter
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
return str(f"{current_time} – data {iCounter}")
if __name__ == "__main__":
stateThread = threading.Thread(target=mainSum)
stateThread.daemon = True
stateThread.start()
webThread = threading.Thread(target=startWebServer)
webThread.start()

So at this point, you may think: why does El Bruno need this? So, let’s share an image that I’ll use in future posts:

thermal camera demo

Note: Some very smart people also suggested to implements this using FastAPI instead of Flask, so a future post may include this.

Happy coding!

Greetings

El Bruno

More posts in my blog ElBruno.com.

More info in https://beacons.ai/elbruno


Resources

7 comments

  1. Ik got a syntax error this cde
    pi@raspberrypi:~/test $ sudo python threading.py
    File “threading.py”, line 20
    print(str(f”{current_time} – data {iCounter}”))
    ^
    SyntaxError: invalid syntax

    Liked by 1 person

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: