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

Buy Me A Coffee

Hi !

After my yesterday post using Flask, I was sure that a FastAPI version will be needed, so here it goes:

I have a common scenario which involves:

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

Read my previous posts to understand why I think this is the 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
# simple webserver with fastapi
# run with uvicorn 07:app -reload
# test with http://127.0.0.1:8000/getdata
# on each call, validate if the thread is started,
# of the thread is None, start a different thread +1 a shared var
from typing import Optional
from fastapi import FastAPI
import threading
import time
stateThread = None
iCounter = 0
app = FastAPI()
def validateStateThread():
global stateThread
if (stateThread is None):
print(f"start thread")
stateThread = threading.Thread(target=mainSum)
stateThread.daemon = True
stateThread.start()
@app.get("/getdata")
def main():
global iCounter
validateStateThread()
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
return str(f"{current_time} – data {iCounter}")
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)

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

Happy coding!

Greetings

El Bruno

More posts in my blog ElBruno.com.

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


Resources

Advertisement

1 comment

  1. Hi El Bruno, I came across your awesome blog while I am searching how to share information to background thread from Flask Webapp entry function. I would like to refer your work ( reference image in this blog , Thermal Detector Labs ) . I have searched entire posts, but I could not find it. Kindly share your approach for sharing the frames captured from the webcam to background work and to display it result in new window. Thank you.

    Like

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 )

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: