How to backup database periodically on PythonAnyWhere server

schedule database backup 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.

we need to run this command in home directory.

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

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  format in file name.

Create the file name and run the backup command using os  package of python.

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.

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.

Or we use the below logic.

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.

 

Restoring database backup:

You can restore the database backup using below command.

 

Complete code of the above script is available on github.

 

References:
[1] https://help.pythonanywhere.com/pages/MySQLBackupRestore/

 

(Visited 277 times, 1 visits today)

You must read this :

Leave a Reply

Your email address will not be published. Required fields are marked *