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