Skip to content

Instantly share code, notes, and snippets.

@reinbach
Created March 7, 2012 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reinbach/90b45a8259ad0b906554 to your computer and use it in GitHub Desktop.
Save reinbach/90b45a8259ad0b906554 to your computer and use it in GitHub Desktop.
Python script to backup PostgreSQL databases
#!/usr/bin/env python
#
# script backs up a list of databases to a specified dir
#
# for the pg_dump call if a password is required, make use
# of a .pgpass file located in the user's home dir that
# is running this script
# see http://www.postgresql.org/docs/8.4/static/libpq-pgpass.html
#
import datetime
import subprocess
import psycopg2
import sys
EXCLUDE_DATABASES = ('template1', 'template0', 'postgres')
DATABASE_HOST = "localhost"
DATABASE_USER = ""
DATABASE_PASS = ""
BACKUP_DIR = "/tmp/"
# get list of databases to backup
# run pg_dump to backup databases to backup dir
def get_db_conn():
conn_string = "host='{host}' user='{user}' password='{password}'".format(
host=DATABASE_HOST,
user=DATABASE_USER,
password=DATABASE_PASS
)
try:
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
return cursor
except:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
sys.exit("Database connection failed!\n ->{error}".format(
error=exceptionValue
))
def main():
cursor = get_db_conn()
cursor.execute("SELECT datname FROM pg_database")
results = cursor.fetchall()
for database in results:
if database[0] not in EXCLUDE_DATABASES:
try:
backup_file = "{backup_dir}{database}{version}.sql".format(
database=database[0],
backup_dir=BACKUP_DIR,
version=datetime.date.today().weekday()
)
subprocess.call("pg_dump -U {user} {database} > {backup_file}".format(
user=DATABASE_USER,
database=database[0],
backup_file=backup_file
), shell=True)
except:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
sys.exit("Database backup failed for {database}!\n ->{error}".format(
database=database[0],
error=exceptionValue
))
print("{database} -> {backup_file}".format(
database=database[0],
backup_file=backup_file
))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment