Files
ihrm/horilla_backup/pgdump.py

39 lines
866 B
Python
Raw Permalink Normal View History

import os
2025-02-14 10:01:07 +05:30
import subprocess
2025-02-14 10:01:07 +05:30
def dump_postgres_db(
db_name, username, output_file, password=None, host="localhost", port=5432
):
# Set environment variable for the password if provided
2025-02-14 10:01:07 +05:30
if password:
os.environ["PGPASSWORD"] = password
# Construct the pg_dump command
dump_command = [
2025-02-14 10:01:07 +05:30
"pg_dump",
"-h",
host,
"-p",
str(port),
"-U",
username,
"-F",
"c", # Custom format
"-f",
output_file,
db_name,
]
try:
# Execute the pg_dump command
2025-02-14 10:01:07 +05:30
result = subprocess.run(
dump_command, check=True, text=True, capture_output=True
)
except subprocess.CalledProcessError as e:
pass
finally:
# Clean up the environment variable
2025-02-14 10:01:07 +05:30
if password:
del os.environ["PGPASSWORD"]