Advertisement
trubliphone

backup django db script

Jan 7th, 2016
1,018
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.89 KB | None | 0 0
  1. # get Django loaded...
  2.  
  3. import os
  4. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
  5.  
  6. # now load other stuff...
  7.  
  8. import datetime
  9. from django.conf import settings
  10. from subprocess import check_call, CalledProcessError
  11. from my_project.my_app.utils import MyCustomError
  12.  
  13. rel = lambda *x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
  14.  
  15. # global variables...
  16.  
  17. ENV = os.environ.copy()  # work on a copy ENV in-case I can't or don't want to change global settings
  18. TIMESTAMP = datetime.datetime.now().strftime("%Y-%m-%d-%H%M")
  19. BACKUP_DIR = rel('../backups/')
  20.  
  21. # get db details...
  22.  
  23. try:
  24.     db_conf = settings.DATABASES["default"]
  25. except KeyError:
  26.     msg = "unable to find valid database configuration"
  27.     raise MyCustomError(msg)
  28. db_backend = db_conf.get("ENGINE")
  29.  
  30. # figure out the cmds for backing up the specific db...
  31.  
  32. if 'postgres' in db_backend:
  33.  
  34.     print("backing up a postgres db...")
  35.  
  36.     backup_file = os.path.join(BACKUP_DIR, "backup_{0}_{1}.sql.tgz".format(db_conf.get("NAME"), TIMESTAMP))
  37.     backup_cmd = "/usr/bin/pg_dump"
  38.  
  39.     # note the use of "-O" which does not constrain table ownership
  40.     # however, the docs of pg_dump state:
  41.     #  <snip>
  42.     #  This option is only meaningful for the plain-text format.
  43.     #  For the archive formats, you can specify the option when you call pg_restore.
  44.     #  </snip>
  45.  
  46.     backup_args = [
  47.         "-Ft",
  48.         "-v",
  49.         "-b",
  50.         "-c",
  51.         "-O",
  52.         "-h{0}".format(db_conf.get("HOST")),
  53.         "-p{0}".format(db_conf.get("PORT")),
  54.         "-U{0}".format(db_conf.get("USER")),
  55.         "-w",
  56.         "-f{0}".format(backup_file),
  57.         db_conf.get("NAME"),
  58.     ]
  59.  
  60.     ENV["PGPASSWORD"] = db_conf.get("PASSWORD")  # bypass manually inputting pwd by using '-w' flag w/ an ENV variable
  61.  
  62. elif "sqlite" in db_backend:
  63.  
  64.     print("backing up a sqlite db...")
  65.     msg = "you don't need a fancy script to backup sqlite; just copy the file"
  66.     raise MyCustomError(msg)
  67.  
  68. elif "mysql" in db_backend:
  69.  
  70.     print("backing up a mysql db...")
  71.     msg = "this script cannot handle mysql yet"
  72.     raise MyCustomError(msg)
  73.  
  74. else:
  75.  
  76.     msg = "unknown db backend: '{0}'".format(db_backend)
  77.     raise MyCustomError(msg)
  78.  
  79. backup_args.insert(0, backup_cmd)
  80.  
  81. # open the logfile and perform the actual backup...
  82.  
  83. with open(os.path.join(BACKUP_DIR, "log.txt"), 'a') as log_file:
  84.  
  85.     try:
  86.         check_call(backup_args, env=ENV)
  87.         msg = "successfully created '{0}'".format(backup_file)
  88.         print(msg)
  89.         log_file.write(TIMESTAMP + ": " + msg)
  90.     except OSError:
  91.         msg = "unable to find {0}".format(backup_cmd)
  92.         raise MyCustomError(msg)
  93.     except CalledProcessError as e:
  94.         msg = "error creating '{0}'".format(backup_file)
  95.         print(msg)
  96.         log_file.write(TIMESTAMP + ": " + msg)
  97.  
  98. # clean up...
  99.  
  100. log_file.closed
  101.  
  102. # hooray, you're done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement