Run while loop concurrently with Flask server

后端 未结 2 1727
心在旅途
心在旅途 2020-12-16 04:33

I\'m updating some LEDs using python. I\'ve been doing this like so:

from LEDs import *
myLEDs = LEDs()
done = False
while not done:
  myLEDs.iterate()


        
相关标签:
2条回答
  • 2020-12-16 04:57

    Use multiprocess to run the loop in a different process as the Flask HTTP requests:

    import time
    from flask import Flask, jsonify
    from multiprocessing import Process, Value
    
    
    app = Flask(__name__)
    
    
    tasks = [
       {
          'id': 1,
          'title': u'Buy groceries',
          'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 
          'done': False
       },
       {
          'id': 2,
          'title': u'Learn Python',
          'description': u'Need to find a good Python tutorial on the web', 
          'done': False
       }
    ]
    
    
    @app.route('/todo/api/v1.0/tasks', methods=['GET'])
    def get_tasks():
       return jsonify({'tasks': tasks})
    
    
    def record_loop(loop_on):
       while True:
          if loop_on.value == True:
             print("loop running")
          time.sleep(1)
    
    
    if __name__ == "__main__":
       recording_on = Value('b', True)
       p = Process(target=record_loop, args=(recording_on,))
       p.start()  
       app.run(debug=True, use_reloader=False)
       p.join()
    

    The tasks part is from here, multiprocessing code from me.
    Note the "use_reloader=False" part. This is necessary to avoid running the loop twice. For the reason see here

    The functionality can be tested by starting up the server with

    python <your_name_for_the example>.py
    

    and calling

    curl -i http://localhost:5000/todo/api/v1.0/tasks
    
    0 讨论(0)
  • 2020-12-16 04:57

    Although I am not the most qualified to comment here: I think this might help you.

    How to run recurring task in the Python Flask framework?

    0 讨论(0)
提交回复
热议问题