Python指令碼實現自動將Database Backup到 Dropbox

來源:互聯網
上載者:User
最近,正好發生了一件大事,就是 GitLab 的營運同學不小心刪除了生產的資料,雖然 GitLab 已經駭人聽聞的準備了五種備份機制,但是,仍然導致他們丟失了將近 6 個小時的使用者資料,尤其對他們聲譽的損失,是根本無法估量的。反思一下,這個部落格 Becomin' Charles,也是沒有完善的備份的,真是冷汗直冒啊,主要考慮到這是我的個人部落格,但是想想已經堅持了快十年了,如果真的丟了的話,還是非常痛心的。

正好,老婆最近正在學習Python 編程,我在教她,其實,我是PHP 程式員,一點也不喜歡 Python,但是說實在,一個外行學編程的話,Python 確實比PHP 友好太多了,只能推薦她學 Python 了。正好,藉著這個機會,我決定自己也學學 Python 編程吧,於是,我決定要用 Python 做一個資料庫的自動備份指令碼。備份的位置,就用Dropbox 來做吧,因為我的伺服器是 Linode 提供的,美國 fremont 機房,選擇美國的儲存服務,比較合適。以下是我寫得代碼,Python 小白,敬請指教:

#!/usr/bin/python#coding:utf-8  import sysimport osfrom yamlimport loadfrom datetime import datetimeimport dropboxfrom dropbox.filesimport WriteModefrom dropbox.exceptions import ApiError, AuthError  if len(sys.argv) < 2:  print >>sys.stderr, "Usage: %s <config_file>" % sys.argv[0]  sys.exit(0)  conf = load(file(sys.argv[1], 'r'))  # config file is a YAML looks like# ---# server-name: 127.0.0.1# local-backup-path: /tmp# remote-backup-path: /backup# dropbox-token: jdkgjdkjg# databases:#  - host:  localhost#   port:  3306#   user:  user#   pass:  password#   name:  database1#   charset: utf8#  - host:  localhost#   port:  3306#   user:  user2#   pass:  password2#   name:  database2#   charset: utf8  for dbin conf['databases'] :  filename = "%s_%s.sql" % (db['name'], datetime.now().strftime("%Y%m%d-%H-%M-%S"))   filepath = "%s/%s" % (conf['local-backup-path'], filename)  cmd = "mysqldump -h%s -u%s -p%s -P%s --single-transaction %s > %s" % (      db['host'],      db['user'],       db['pass'],       db['port'],       db['name'],       filepath      )  os.system(cmd)  cmd = "gzip %s" % filepath  os.system(cmd)  filepath = filepath + '.gz'  dbx = dropbox.Dropbox(conf['dropbox-token'])  backuppath = "%s/%s/%s/%s" % (      conf['remote-backup-path'],    # remote path      datetime.now().strftime("%Y%m%d"), # date string      conf['server-name'],       # server name      filename + '.gz')  with open(filepath, 'rb') as f:    time = datetime.now().strftime("%Y-%m-%d %H:%M:%S ")    print(time + "Uploading " + filepath + " to Dropbox as " + backuppath)    try:      dbx.files_upload(f.read(), backuppath, mode=WriteMode('overwrite'))    except ApiErroras err:      # This checks for the specific error where a user doesn't have      # enough Dropbox space quota to upload this file      if (err.error.is_path() and          err.error.get_path().error.is_insufficient_space()):        sys.exit("ERROR: Cannot back up; insufficient space.")      elif err.user_message_text:        print(err.user_message_text)        sys.exit()      else:        print(err)        sys.exit()

簡單描述下這個代碼的思路,這個程式應該滿足這個幾個要求:

使用 mysqldump 備份資料庫到本地

應該支援設定檔,允許配置多個資料庫

可以上傳到 Dropbox

為了完成這些要求,首先碰到的難題是怎麼支援設定檔,一搜,原來 Python 下有個預設的 ConfigParser,可以完成這個任務,但是正常東西比較噁心的是,設定檔必須是以 [Section] 為單位組織的。其實我的配置顯然有些全域配置,還有就是資料庫的各種資訊是多次重複的,這種設定檔,嵌套能力簡直糟糕,必須兩層的結構,就很噁心。於是我去網上搜設定檔的格式,好多文章比較了各種設定檔的優劣,其實這文章挺多的,我想了想,以後或許我也可以寫文章講講我自己的感受了。反正就是很多文章最後都公認 YAML 是設定檔裡最完美的。於是我也決定用這個,果然也有現成的類庫,就是 PyYAML,特方便,就倆函數 load 和 dump,直接就把檔案變成 dict 格式了。

第二個難題,就是上傳 Dropbox,後來發現,官方提供了很豐富的 API,而且直接就有 SDK,(讓我眼紅的是,官方竟然沒有 PHP 的 SDK,這麼不受待見嗎?),研究 SDK 用法,發現直接就有代碼範例,於是直接抄到My Code裡,瞬間完成了 50% 的代碼,爽!

整個程式碼完成後,我發現,寫代碼一共也沒花多少時間,而且,我學會的 Python 的方式,我以前一直抱怨 Python 的文檔難用,我發現,其實,最好的方式其實是在互動 Shell 裡,用 help 來查詢 API,再輔佐以官方文檔,才是比較正確的方式。這是重新整理了一個我以前的認識的地方。實踐下來感覺還不錯的。Python 的包管理器 pip 也很好用。

pip install PyYAMLpip install dropbox

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.