Last active
August 29, 2015 14:26
-
-
Save ironicbadger/b0efc3adcbfaabbdb3cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import psycopg2 | |
import sys | |
import time | |
host = '192.168.1.40' | |
dbname = 'my_db' | |
user = 'my_pg_user' | |
password = 'my_pg_user_pass' | |
port = 5432 | |
def main(): | |
test_connection() | |
def retry(howmany): | |
def tryIt(func): | |
def f(): | |
attempts = 0 | |
while attempts < howmany: | |
try: | |
return func() | |
except: | |
attempts += 1 | |
return f | |
return tryIt | |
@retry(10) | |
def test_connection(): | |
#Define our connection string | |
conn_string = "host='%s' dbname='%s' user='%s' password='%s' port='%i'"\ | |
% (host, dbname, user, password, port) | |
# print the connection string we will use to connect | |
print("Connecting to database\n ->%s" % (conn_string)) | |
try: | |
# get a connection, if a connect cannot be made an exception will be raised here | |
conn = psycopg2.connect(conn_string) | |
# conn.cursor will return a cursor object, you can use this cursor to perform queries | |
cursor = conn.cursor() | |
print "Connected!\n" | |
except: | |
failures++ | |
# Get the most recent exception | |
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() | |
# Exit the script and print an error telling what happened. | |
sys.exit("Database connection failed!\n ->%s" % (exceptionValue)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment