backup_pg_to_s3.py 892 B

1234567891011121314151617181920212223242526272829303132333435
  1. import os, gzip, boto3, uuid
  2. from sh import pg_dump
  3. class PGBackupDB:
  4. def __init__(self, s3_bucket_name, db_backup_file_path, pg_user, pg_pass, pg_db_name):
  5. self.s3_bucket_name = s3_bucket_name
  6. self.db_backup_file_path = db_backup_file_path
  7. self.pg_user = pg_user
  8. self.pg_pass = pg_pass
  9. self.pg_db_name = pg_db_name
  10. def create_db_backup(self):
  11. os.putenv("PGPASSWORD",self.pg_pass)
  12. # Backup Postgres DB to gzipped file
  13. with gzip.open(self.db_backup_file_path, "wb") as f:
  14. pg_dump("-h", "localhost", "-U", self.pg_user, self.pg_db_name, _out=f)
  15. def push_backup_to_s3(self):
  16. # Connect to S3
  17. s3 = boto3.client("s3")
  18. # Push DB to S3
  19. s3_file_name = "db-%s.gz" % (str(uuid.uuid4()))
  20. s3.upload_file(self.db_backup_file_path, self.s3_bucket_name, s3_file_name)
  21. def delete_db_backup(self):
  22. os.remove(self.db_backup_file_path)