Reload python flask server by function Reload python flask server by function flask flask

Reload python flask server by function


I think I've had the same problem.

So there was a python/flask application (XY.py), on clients. I wrote a build step (Teamcity) which deploys this python code to the clients. Let's suppose the XY.py is already running on the clients. After deploying this new/fixed/corrected XY.py I had to restart it for applying the changes on the running code.

The problem what I've had is that after using the fine restarting oneliner os.execl(sys.executable, *([sys.executable]+sys.argv)) my port used by app is still busy/established, so after restarting I can't reach it.

This is how I resolved the problem:I put my app to run on a separate Process and made a queue for it. To see it more cleanly here is some code.

global some_queue = None@app.route('/restart')def restart():   try:     some_queue.put("something")     return "Quit"def start_flaskapp(queue):   some_queue = queue   app.run(your_parameters)

Add this to your main:

q = Queue()p = Process(target=start_flaskapp, args=[q,])p.start()while True: #wathing queue, sleep if there is no call, otherwise break   if q.empty():         time.sleep(1)   else:      breakp.terminate() #terminate flaskapp and then restart the app on subprocessargs = [sys.executable] + [sys.argv[0]]subprocess.call(args)

Hope it was clean and short enough and it helped to you!


How following in your Python code in order to kill the server:

@app.route('/quit')def _quit():    os._exit(0)

When process is killed it will repeat itself in the while loop.

app_run.sh:

#!/bin/bashwhile truedo    hypercorn app_async:app -b 0.0.0.0:5000     sleep 1done