· 8 years ago · Feb 21, 2017, 06:52 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 const
11APP_KEY = const.KEY
12APP_SECRET = const.SECRET
13
14
15ACCESS_TYPE = 'app_folder'
16sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
17
18oauth_token = ''
19oauth_token_secret = ''
20
21f = open("dropbox_token.txt",'r')
22if f:
23 oauth_token = string.strip(f.readline())
24 oauth_token_secret = string.strip(f.readline())
25 f.close()
26
27if oauth_token == '' or oauth_token_secret == '':
28 request_token = sess.obtain_request_token()
29
30 url = sess.build_authorize_url(request_token)
31 print "url:", url
32 print "Please visit this website and press the 'Allow' button, then hit 'Enter' here."
33 raw_input()
34 access_token = sess.obtain_access_token(request_token)
35 f = open("dropbox_token.txt","wb")
36 f.write(access_token.key + '\n')
37 f.write(access_token.secret)
38 f.close()
39else:
40 sess.set_token(oauth_token, oauth_token_secret)
41
42client = client.DropboxClient(sess)
43
44USER = const.USER
45PASS = const.PASS
46HOST = const.HOST
47
48BACKUP_DIR = const.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 = [const.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
68
69f = open(file_name,'rb')
70if f:
71 fsize = getsize(file_name)
72 uploader = client.get_chunked_uploader(f, fsize)
73 print "Uploading file", fsize, "bytes..."
74 while uploader.offset < fsize:
75 try:
76 upload = uploader.upload_chunked()
77 print "."
78 except rest.ErrorResponse, e:
79 print "error uploading file!"
80 uploader.finish("/"+file_name)
81 f.close()
82 print "File uploaded successfully."