V
V
Vitaly2018-08-21 12:29:03
Python
Vitaly, 2018-08-21 12:29:03

What is the correct way to use queues in Flask python?

All the best! Please tell me how to use queues in conjunction with Flask.
I sort of ripped them to my Flask server, but I'm not sure if it's right.
Here is an example of my implementation:

from Queue import Queue
import threading
from flask import Flask


class Sender(object):
    def send(self):
        # sending...
        return "sended"




senderManager = Sender()


app = Flask(__name__)


q = Queue()
t = threading.Thread(target=q_worker)
t.setDaemon(True)
t.start()

def send_command(item):
    senderManager.send(item)


def q_worker():
    while True:
        item = q.get()
        send_command(item)
        q.task_done()






@app.route("/action", methods=['POST'])
def action():
    item = request.json['item']
    q.put(item)

    return "added to q"

q.join()

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

It is necessary that when a request for /action is received , send actions through the send method (sending a command to the hardware) of the Sender class , the process of which takes some time, and if they do not wait for its execution and call this method again (when receiving the next POST request), a new sender will not work correctly, since the hardware to which the previous command was sent has not finished working yet, and the new command will simply not be executed. Therefore, it is necessary that when receiving several POST requests in a row, a queue is created, and a new Sender.send from this queue is gradually executed, only after the previous one has been completed.
PS Especially not sure about the locationq.join()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Дмитрий, 2018-08-21
@dmtrrr

Если у вас будет больше одного процесса с Flask приложением (а так скорее всего и должно быть), то у каждого процесса будет своя очередь, и все это будет работать не так, как вам нужно.
Самый простой способ писать события в БД, и скрипт по крону будет отправлять команды железу.
Если по скорости такой вариант не подходит, смотрите в сторону RabbitMQ

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question