-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup.py
More file actions
70 lines (61 loc) · 2.7 KB
/
Copy pathbackup.py
File metadata and controls
70 lines (61 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import os
import datetime
import daemon
import time
import backup_config as conf
class MySQLBackup:
def __init__(self):
self.db_user = conf.db_user
self.db_pass = conf.db_pass
self.db_name = conf.db_name
self.tg_token = conf.tg_token
self.chat_id = conf.chat_id
self.backup_folder = conf.backup_folder
self.wait_time = conf.wait_time
self.bckp_filename = ''
@staticmethod
def generate_backup_filename():
"""
Generate backup filename with extension
Using datetime snapshot as filename + .sql
:return: string
"""
return str(datetime.datetime.now()).replace(' ', '+').replace(':', '') + '.sql'
def make_backup(self):
"""
Make fast database backup as sql file.
Using mysqldump utility.
:return: None
"""
self.bckp_filename = self.generate_backup_filename()
os.system('mysqldump --user {user} --password={password} {db_name} > {output}'.format(user=self.db_user,
password=self.db_pass,
db_name=self.db_name,
output=os.path.join(
self.backup_folder,
self.bckp_filename))
)
def send_backup(self):
"""
Send backup to target Telegram chat using Telegram Bot API.
:return: None
"""
os.system('curl -v -F "chat_id={chat_id}" -F document=@{file_path} '
'https://api.telegram.org/bot{token}/sendDocument'.format(chat_id=self.chat_id,
file_path=os.path.join(self.backup_folder,
self.bckp_filename),
token=self.tg_token))
def main(self):
"""
Main loop function to make backup each wait_time interval
:return: None
"""
while True:
self.make_backup() # create .sql backup
self.send_backup() # send using tg bot API
time.sleep(self.wait_time) # waiting interval
if __name__ == '__main__':
bk = MySQLBackup()
# run script in background
with daemon.DaemonContext():
bk.main()