0

I am working on a Flask app which starts as soon as Nvidia Jestson bootsup. There are 2 threads : 1. serial read continually gets the values from uart and updates the web page

  1. backgroundthread which does some calculation based on the values got from the html form.

My code goes something like this:

thread1 = Thread()
thread2 = Thread()
thread1_stop_event = Event()

class serial_read_Thread(Thread):

    def __init__(self):
        self.delay = 0.1
        self.port = serial.Serial ( port='/dev/ttyTHS2', baudrate=115200, 
                                   parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
                                   bytesize=serial.EIGHTBITS, timeout=1)

        super(serial_read_Thread, self).__init__()

    def serial_read (self):
        try:
            x = self.port.read().decode()
            recvd_string += x
            #receive the list as string and convert it to list
            for val in range(1, len(recvd_string)):
                if (val % 2 != 0):
                    index = int(float(recvd_string[val]))
                else:
                    received_signal_values[index] = recvd_string[val]

            number1 = received_signal_values[0]
            number2 = received_signal_values[1]
            socketio.emit('newnumber', {'number1':number1, 'number2':number2}, namespace='/test')
            time.sleep(self.delay)
        except UnicodeDecodeError:
            print("UnicodeDecodeError \n")
            pass

    def run(self):
        self.serial_read()


class Backgroundthread(Thread):

    def __init__(self):
        super(Backgroundthread, self).__init__()

    def process_data(self):
        do_calculation()

    def run(self):
        self.process_data()


@app.route("/", methods=['GET', 'POST'])
def hello():
    form = TestForm()
    global thread2

    if request.method == 'POST':
        Get the values from the html form 

        if not thread2.isAlive():
           thread2 = Backgroundthread()
           thread2.start()

    return render_template('hello.html', form=form)


@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread1
    print('Client connected')

    #Start the serial read thread 
    print("Starting Serial Read Thread")
    thread1 = serial_read_Thread()
    thread1.daemon = True
    thread1.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')

if __name__== "__main__":
  socketio.run(app)

When I manually run the code I see the Web-browser with my page loaded, the values being updated from the serial thread. Also when I input the values through the web page I see the background thread being processed. But the same does not work when I run the code from the startup script on Jetson. I see the webpage with values being updated but when I input the values from the html form I do not see the background thread being processed. Also I would like to know if this is a correct way to merge threads with the flask app. Sorry for the long post. Thanks in advance

1 Answer 1

1

Flask is just the framework for handling the requests. Although it has a built-in webserver fpr debugging it is not essentially a webserver. On my production flask apps i generally use gevent to be the webserver for my flask app. So depending on the webserver, a different strategy for serving the requests will be used. Either using a single thread per request, reusing previous allocated threads, a single process per request or anything else...Thats why I recommended to not use threads inside the flask app.

So i suggest you try to find a way to keep your endpoints stateless and do not use threads at all.

Still if you really need or want to process something in parallel I have a solution for your problem, you do can start a python subprocess from your endpoint. It gonna run in parallel no matter the webserver strategy. I used this strategy on my database-to-database importing api. The endpoints validate the payload and start a subprocess that will solve the problem. Then the endpoint returns a key to follow the process through the database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.