I have a simple flask app that I want to restart if the server port is changed in a config file. I have the following code:
#!/usr/bin/env python
from flask import Flask, jsonify
import sys, time, os
app = Flask(__name__,static_url_path='')
HTTPPort = 8080
#------------------------------------------------------------
@app.route("/cmd/<command>")
def command(command):
if command == "restart":
Reload()
return jsonify("OK")
#------------------------------------------------------------
def Reload():
# reload python script
os.execl(sys.executable, 'python', __file__, *sys.argv[1:])
#------------------------------------------------------------
if __name__ == "__main__":
# load options from file, which change HTTPPort value
# LoadConfig()
while True:
try:
app.run(host="0.0.0.0", port=HTTPPort)
except Exception as e1:
print("Error in app.run:" + str(e1))
time.sleep(2)
Reload()
The problem is that when os.execl is called it reloads the python script but app.run fails with "[Errno 98] Address already in use"
Once the app is loaded you can trigger the command routine in a browser by entering in the address windows of the browser :8080/cmd/restart . This will cause the flask app to accept the "restart" command, which will cause os.exec() to be called. At this point the app will terminate and reload. On the reload app.run() will error out with "Address already in use" via the exception and it will try to reload every 2 seconds, same error every time.
I tried setting reload= True in the app.run argument list however this would not allow the port to be changed. Is this possible to accomplish or am I doing something wrong?
Thanks
app.run()in thewhileloop and spawning a new process?