· 8 years ago · Feb 21, 2017, 08:38 PM
1#-*-coding: utf-8-*-
2
3import os
4import string
5from os.path import getsize
6from time import gmtime, strftime
7import subprocess
8from dropbox import client, rest, session
9import ConfigParser
10
11config = ConfigParser.RawConfigParser()
12config.read('const.cfg')
13
14APP_KEY = config.get('Section1', 'KEY')
15APP_SECRET = config.get('Section1', 'SECRET')
16
17ACCESS_TYPE = 'app_folder'
18sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
19
20oauth_token,oauth_token_secret = '', ''
21
22oauth_token = config.get('Section1', 'token')
23oauth_token_secret = config.get('Section1', 'token_secret')
24
25
26if oauth_token == '' or oauth_token_secret == '':
27 request_token = sess.obtain_request_token()
28
29 url = sess.build_authorize_url(request_token)
30 print "url:", url
31 print "Please visit this website and press the 'Allow' button, then hit 'Enter' here."
32 raw_input()
33 access_token = sess.obtain_access_token(request_token)
34
35 config.set('Section1', 'token', access_token.key)
36 config.set('Section1', 'token_secret', access_token.secret)
37 with open('const.cfg', 'wb') as configfile:
38 config.write(configfile)
39else:
40 sess.set_token(oauth_token, oauth_token_secret)
41
42client = client.DropboxClient(sess)
43
44USER = config.get('Section1', 'USER')
45PASS = config.get('Section1', 'PASS')
46HOST = config.get('Section1', 'HOST')
47
48BACKUP_DIR = config.get('Section1', 'backup')
49dumper = """ pg_dump -U %s -Z 9 -f %s -F c %s -h %s """
50
51def log(string):
52 print strftime("%Y-%m-%d-%H-%M-%S", gmtime()) + ": " + str(string)
53
54os.putenv('PGPASSWORD', PASS)
55database_list = [config.get('Section1', 'dbname')]
56
57for database_name in database_list :
58 log("dump started for %s" % database_name)
59 thetime = str(strftime("%Y-%m-%d-%H-%M"))
60 file_name = database_name + '_' + thetime + ".sql.pgdump"
61 command = dumper % (USER, BACKUP_DIR + file_name, database_name, HOST)
62 #log(command)
63 subprocess.call(command,shell = True)
64 log("%s dump finished" % database_name)
65
66log("Backup job complete.")
67
68with open(file_name,'rb') as f:
69 fsize = getsize(file_name)
70 uploader = client.get_chunked_uploader(f, fsize)
71 print "Uploading file", fsize, "bytes..."
72 while uploader.offset < fsize:
73 try:
74 upload = uploader.upload_chunked()
75 print "."
76 except rest.ErrorResponse, e:
77 print "error uploading file!"
78 uploader.finish("/"+file_name)
79 f.close()
80 print "File uploaded successfully."