import psycopg2 host = 'localhost' db = 'your_db' user = 'your_username' password = 'your_pw' connect_string = "dbname='%s' user='%s' host='%s' password='%s'" % ( db, user, host, password ) def connect_db(): try: connection = psycopg2.connect(connect_string) except Exception, e: print "Error connection to db!" raise else: print "Successfull connection" return connection