Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of an infinite loop with flask and python using http?

I would like to break out of an infinite loop using flask and a http get.

from flask import Flask, render_template, jsonify
from serialtest import get_dist
app = Flask(__name__)

def test():
    while True:
        print('keep going!')

@app.route('/start')
def start():
    return test()

@app.route('/stop')
def stop():
    # stop the function test
    return 'stopped'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)

I want to use Flask as a http server and serve a web client that can start test() with a click event and http get, then stop test() with a different click event.

like image 884
apollowebdesigns Avatar asked Jan 28 '23 10:01

apollowebdesigns


1 Answers

For this particular case you can spawn a thread that handles the long running task. i.e.,

import threading
import time
from flask import Flask, render_template, jsonify
from serialtest import get_dist
app = Flask(__name__)

light_on = False

@app.before_first_request
def light_thread():
    def run():
        global light_on
        while light_on:
            print("keep going!")
            time.sleep(1)

    thread = threading.Thread(target=run)
    thread.start()

@app.route('/start')
def start():
    # stop the function test
    light_on = True
    return "started"

@app.route('/stop')
def stop():
    light_on = False
    return 'stopped'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)

The thread runs as long as the server itself is running and is started before any HTTP request is made to the server using the before_first_request decorator. It checks the on/off state in a global variable. I wouldn't recommend this, specifically using the global variable to save state, for all scenarios but this should accomplish the use case you've described.

like image 85
thedouglenz Avatar answered Feb 13 '23 03:02

thedouglenz