how-to database backup   0   177
How to backup database periodically on PythonAnyWhere server

You can host your Django app effortlessly on PythonAnyWhere server. If you are using the database in your app then it is strongly recommended to take backup of database to avoid loss of data.

This PythonAnyWhere article explain the process to take sql dump. We will extend the same article to take database backup periodically and delete the old files.

As explained in the article we can use below command to take backup.

mysqldump -u yourusername -h 'yourusername$dbname'  > db-backup.sql

We need to run this command in home directory.

To take the backup periodically, we will write a small script.


First lets create a directory in home where all the backup files will reside. Lets name is mysql_backups. Now in script, define the variables like backup directory name, file prefix and file suffix etc.

To distinguish, we will append the time stamp in yyyymmddHHMMSS  ormat in file name. Create the file name and run the backup command using os  package of python.

import os
import datetime
from zipfile import ZipFile

BACKUP_DIR_NAME = "mysql_backups"
FILE_PREFIX = "my_db_backup_"
USERNAME = "username"

# get today's date and time
timestamp =
backup_filename = BACKUP_DIR_NAME+"/"+FILE_PREFIX+timestamp+".sql"

os.system("mysqldump -u "+USERNAME+" -h "+USERNAME+" '"+DBNAME+"'  > "+backup_filename)

We can test this script by running using the python installed in virtual environment. I strongly recommend to use virtual environment for all your python and Django projects.

Now to save some space we will zip the sql file. For this we will use zipfile  python package.

# creating zip file
zip_filename = BACKUP_DIR_NAME+"/"+FILE_PREFIX+timestamp+".zip"
with ZipFile(zip_filename, 'w') as zip:
    zip.write(backup_filename, os.path.basename(backup_filename))

Now when sql file has been added to zip file, we may delete it.


Now we can schedule this script from tasks tab. Now lets extend the script to delete old files. Define a variable which signifies for how many days we need to keep the backup.


So for now we will keep last three backups. Now there are two ways to delete the old files. Either use the os.stat() function to check when was a file created and if it is older than DAYS_TO_KEEP_BACKUP, delete it.

for f in os.listdir(path):
    if os.stat(os.path.join(path,f)).st_mtime < now - 3 * 86400:

Or we use the below logic.

# deleting old files

list_files = os.listdir(BACKUP_DIR_NAME)

back_date = - 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
for f in list_files:
    filename = f.split(".")[0]
    if "zip" == f.split(".")[1]:
        suffix = filename[length:]
        if suffix < back_date:
            print("Deleting file : "+f)
            os.remove(BACKUP_DIR_NAME + "/" + f)

First get the list of all files in backup directory. Then for each file in list, check if file extension is 'zip' and then compare the file time stamp suffix with the back date. We can always use os.path.splitext()  function to get filename and extension. Its up to you to use whichever way you feel good. Feel free to tweak the script and experiment.

>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
>>> file_extension

Restoring database backup:

You can restore the database backup using below command.

mysql -u yourusername -h 'yourusername$dbname' < db-backup.sql


Complete code of the above script is available on github.  

how-to database backup   0   177

Related Articles:
Python Script 3: Validate, format and Beautify JSON string Using Python
Validating json using python code, format and beautify json file using python, validate json file using python, how to validate, format and beautify json...
Encryption-Decryption in Python Django
How to encrypt and decrypt the content in DJango. Encrypting the critical information in Django App. Encrypting username, email and password in Django...
Adding Robots.txt file to Django Application
Adding robots.txt file in your Django application. Easiest way to add robots.txt file. Django application robots.txt file. Why should you add robots.txt file in your Django Application....
How to upgrade to paid account on PythonAnyWhere
Which is the best server for hosting Django Apps. Best hosting provider for Django Apps. Cheapest Django Hosting. PythonAnyWhere Reviews. Django Hosting....

0 thoughts on 'How To Backup Database Periodically On Pythonanywhere Server'
Leave a comment:

*All Fields are mandatory. **Email Id will not be published publicly.

Please subscribe to get the latest articles in your mailbox.

Recent Posts:

© 2018-2019