dsn = 'dbname=postgres'
conn = psycopg2.connect(dsn)
try:
    connection.isolation_level
except OperationalError as oe:
    conn = psycopg2.connect(dsn)
c = conn.cursor()
c.execute('SELECT 1')
Making sure that psycopg2 database connection alive