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,
  1. threading : to make the function run every 5 seconds
  2. psutil : to get informations regarding processes which are currently running
  3. subprocess : to spawn a new process if our app goes down

So the code looks like :

import threading
import psutil
import subprocess

def autopilot():
    path="<give the path of the app here>"
    threading.Timer(5.0, autopilot).start()
    for pid in psutil.pids():
       if"python" and path in p.cmdline():
           print "running", pid
    if flag==0:
        subprocess.Popen(["nohup","python", path])

You can try it out in your python interpreter what this, p.cmdline() etc means.
Hope everyone enjoyed this delicious recipe which can buy some time for you to sleep..😎
Github link to the code

Thank you..



Popular Posts