Python Backup Script For PostgreSQL Automatically

Do you like this?

Summary:
This post shows you a way to automate backing up your PostgreSQL database on your server and to download it to your local machine.


Content:

This script requires command line inputs. Following is a sample of how to use the script:

postgresql_backup.py  --db_name dbname --db_username dbusername --db_password dbpassword --file_out file.sql --local_dir "\path\to\local\backup\folder"
You can download the file here: Python Backup Script For PostgreSQL Automatically

All the arguments are self explanatory. You just have to change them according to your setup.
import datetime
import os
import logging

class AttributeDict(dict):
    def __init__(self):
        super(AttributeDict,self).__init__()
        __getattr__ = super(AttributeDict,self).__getitem__
        __setattr__ = super(AttributeDict,self).__setitem__

settings= AttributeDict()

def get_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument("-ho", "--host", action="store", type=str)
    parser.add_argument("-d", "--db_name", action="store", type=str)
    parser.add_argument("-du", "--db_username", action="store", type=str)
    parser.add_argument("-dp", "--db_password", action="store", type=str)
    parser.add_argument("-fo", "--file_output", action="store", type=str)
    parser.add_argument("-ld", "--local_dir", action="store", type=str)

    return parser.parse_args(sys.argv[1:])


def download_file_path(args):
    if not os.path.exists (args.local_dir):
        os.mkdir (args.local_dir)
    d = datetime.datetime.now()
    download_file_path= os.path.join(args.local_dir,('%s-%s'%(d.strftime('%Y%m%d%H%M'),args.file_output)))
    return download_file_path

def backup(args):
    file_path= download_file_path(args)
    backup_command= "export PGPASSWORD='%s' && pg_dump -h %s -U %s %s -w --clean> %s" % \
                        (args.db_password,args.host ,args.db_username, \
                         args.db_name, \
                         file_path)
    
    logging.debug('Running command: %s' % backup_command)
    os.system(backup_command)


if __name__ == "__main__":
    args= get_default_arguments()
    
    logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename=os.path.join(args.local_dir,'logging.txt'),
                    filemode='a')

    #setting default values
    if not args.file_output:
        args.file_output= args.db_name

    backup(args)
    

 
comments powered by Disqus