Restart your flask app if it goes down using python
Autopilot script
We can use upstart or supervisor to monitor and control n number of processes.
But in this recipe I will be explaining how to write a python script to monitor a single app, for an example let it be a flask web app.
Our objective is to write a python script which will automatically make the flask app up and running whenever it goes down. So for writing the script we will use 4 packages,
So the code looks like :
Hope everyone enjoyed this delicious recipe which can buy some time for you to sleep..😎
Github link to the code
Thank you..
Our objective is to write a python script which will automatically make the flask app up and running whenever it goes down. So for writing the script we will use 4 packages,
- threading : to make the function run every 5 seconds
- psutil : to get informations regarding processes which are currently running
- subprocess : to spawn a new process if our app goes down
So the code looks like :
import threadingYou can try it out in your python interpreter what this p.name(), p.cmdline() etc means.
import psutil
import subprocess
def autopilot():
flag=0
path="<give the path of the app here>"
threading.Timer(5.0, autopilot).start()
for pid in psutil.pids():
p=psutil.Process(pid)
if p.name()=="python" and path in p.cmdline():
print "running", pid
flag=1
break
if flag==0:
subprocess.Popen(["nohup","python", path])
flag=1
autopilot()
Hope everyone enjoyed this delicious recipe which can buy some time for you to sleep..😎
Github link to the code
Thank you..
Comments
Post a comment