Django database backup view

Friday, 5th September, 2008 // 1:50 a.m.

Tagged: backup , database , django , email , os , python , sql and tar

Finally with some great help from Will Larson and Thejaswi Puthraya I found the problem. Thank you guys. This view now works.

We all backup our databases once in a while. Well there are several ways to take a backup of the database. Most of the people export their database as a .sql file and back it up. Here is a small view I constructed to backup the django database. As far as my requirements are conserened I put together a django view which automatically creates a backup of the database, zip it and then mail it to my email. Sounds cool. Lets get started.

One more important requirement is that this view should be protected. I dont have a django-registration module on my djangp project. But the django by default creates the users table. Only the user with staff permission should be able to execite this view.

def dbbackup(request):
    if not (request.user.is_authenticated() and
          request.user.is_staff):
        raise http.Http404

I am just checking if the user is logged in and also checking if that user has staff permissions. If any one of the condition fails the user sees a 404 page.

from django.conf import settings
import os
os.chdir('/path/to/your/django/root/or/anything')  # This is important as apache by default goes to the user's home directory.
os.popen3("mysqldump --add-drop-table -u " + settings.DATABASE_USER + " -p" +       
  settings.DATABASE_PASSWORD + " " + settings.DATABASE_NAME + " >  backup.sql")
os.popen3("gzip -c backup.sql > backup.gz")

The command to dump a mysql database is mysqldump -u user -p(password) database_name > file_name.sql. Make sure u set the os.cwd using the chdir.

As I am running on webfaction and they run their apache as root, the mod_python was trying to write the backup sql file to root where I dont have write access. This created a mess.

I made sure that the database credentials are brought from the settings file and properly setup. Now we have backup.sql. Then I zip the .sql file using the gzip command.

You might wonder where this zip and sql file reside on you box. Just login to the Django shell,

import os  
os.getcwd()   # Shows the current working directory. In this case it should the django root directory.

Now to the email part. Import the 'EmailMessage' class set the attributes of the class.

from django.core.mail import EmailMessage
subject = "Your DB-backup for " + datetime.now().strftime("%d %b %Y")
body = "Your database back for" + Site.objects.get_current().name + ". Timestamp of the backup is " +   
    datetime.now().strftime("%d %b %Y")
email = EmailMessage(subject, body, 'from@email.com', ['to@email.com'])
email.content_subtype = "html"

So I set the subject and body to contain the name of the site and datestamp of the backup. After constructing the EmailMessage I set the content_subtype to "html".

email.attach_file("backup.gz")
email.send()

I am attaching the tar file as an attachment. For more info check the documentation. Then I simply send the mail. After sending the email we can simply remove the backup.sql and the tar file.

os.system("rm backup.sql")
os.system("rm backup.gz")

After this I render a simple page showing success. Simple ain't it. Just configure a url to this view and you are done

Comment Form

MarkDown syntax enabled

1 comment:

  1. 001// Arne// Saturday, 7th March, 2009, 1 p.m.

    I've put together a simple, reuseable app for exporting the database in a very similar way. The idea to send the backup via email is nice, as long as the dump don't gets too big. Instead of emailing my app supports uploading the dump to Amazon S3 ...

    You can find django-export here: http://github.com/arneb/django-export/

thnknsblvng