Created
April 2, 2019 07:06
-
-
Save Shawn1224/9653734f55c6c891284558024aca3e77 to your computer and use it in GitHub Desktop.
Backup specific tables for pg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
COMMAND_PRE = "pg_dump --column-inserts -a" | |
def backup(host_name, database_name, user_name, port, database_password, tables, file_dir="."): | |
"""backup specific tables for pg | |
Ref: http://wzktravel.github.io/2016/08/23/How-to-pass-in-password-to-pg-dump/ | |
export shell demo: | |
pg_dump --column-inserts -a -h {0} -d {1} -U {2} -p 5432 -t zones_seq -t table_2 > /tmp/zones_seq.sql | |
export file: | |
filename format: | |
port.date.sql | |
e.g: | |
15.2019_03_27_21_39_02.sql | |
Arguments: | |
host_name {string} | |
database_name {string} | |
user_name {string} | |
database_password {string} | |
tables {list/tuple} | |
file_dir {string} | |
""" | |
pg_pwd_env = 'env PGPASSWORD="%s"' % database_password | |
command_con = "-h {0} -d {1} -U {2} -p {3}" | |
command_export_tables = "-t " + " -t ".join(tables) | |
filename = ".".join((port, datetime.now().strftime("%Y_%m_%d_%H_%M_%S"), "sql")) | |
file_path = "/".join((file_dir, filename)) | |
command_full = " ".join((pg_pwd_env, COMMAND_PRE, command_con, command_export_tables, ">", file_path)) | |
command = command_full.format(host_name, database_name, user_name, port) | |
p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) | |
for stdout_line in iter(p.stdout.readline, ""): | |
print(stdout_line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment