forked from anuragrana/Python-Scripts
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb-backup-pythonanywhere.py
More file actions
Latest commit
58 lines (41 loc) · 1.68 KB
/
Copy pathdb-backup-pythonanywhere.py
File metadata and controls
58 lines (41 loc) · 1.68 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
importos
importdatetime
fromzipfileimportZipFile
#
# Author - Anurag Rana
# anuragrana31189 at gmail dot com
# place in home directory. schedule with task tab on pythonanywhere server.
# https://www.pythoncircle.com/post/360/how-to-backup-database-periodically-on-pythonanywhere-server/
#
BACKUP_DIR_NAME="mysql_backups"
DAYS_TO_KEEP_BACKUP=3
FILE_PREFIX="my_db_backup_"
FILE_SUFFIX_DATE_FORMAT="%Y%m%d%H%M%S"
USERNAME="username"
DBNAME=USERNAME+"$dbname"
# get today's date and time
timestamp=datetime.datetime.now().strftime(FILE_SUFFIX_DATE_FORMAT)
backup_filename=BACKUP_DIR_NAME+"/"+FILE_PREFIX+timestamp+".sql"
os.system("mysqldump -u "+USERNAME+" -h "+USERNAME+".mysql.pythonanywhere-services.com '"+DBNAME+"' > "+backup_filename)
# creating zip file
zip_filename=BACKUP_DIR_NAME+"/"+FILE_PREFIX+timestamp+".zip"
withZipFile(zip_filename, 'w') aszip:
zip.write(backup_filename, os.path.basename(backup_filename))
os.remove(backup_filename)
# deleting old files
list_files=os.listdir(BACKUP_DIR_NAME)
back_date=datetime.datetime.now() -datetime.timedelta(days=DAYS_TO_KEEP_BACKUP)
back_date=back_date.strftime(FILE_SUFFIX_DATE_FORMAT)
length=len(FILE_PREFIX)
# deleting files older than DAYS_TO_KEEP_BACKUP days
forfinlist_files:
filename=f.split(".")[0]
if"zip"==f.split(".")[1]:
suffix=filename[length:]
ifsuffix<back_date:
print("Deleting file : "+f)
os.remove(BACKUP_DIR_NAME+"/"+f)
# restoring backup
# mysql -u yourusername -h yourusername.mysql.pythonanywhere-services.com 'yourusername$dbname' < db-backup.sql
# reference
# https://help.pythonanywhere.com/pages/MySQLBackupRestore/