Starting Django upon Reboot using Cron

Three years ago I wrote about starting services as a user via cron instead of init.d (specifically Trac). However, this method has a serious downside: it has no support for dependencies. This really bothered me when I used cron to start a Django server, as it would attempt to load before MySQL was running. This made cron useless, as after every reboot I would receive an error email saying it couldn’t connect to the MySQL server, and I would have to log in and start the Django server manually. Yesterday I got sick of it and decided to hack something together that will work properly. So my crontab had the following line:

@reboot python ./manage.py runfcgi ...options...

which I changed to:

@reboot until /sbin/status mysql | grep start/running ; do echo "Mysql isn't running yet...>&2"; sleep 1; done; python ./manage.py runfcgi ...options...

Basically, it loops and checks whether the MySQL service has started. If so, it starts Django as it did before. On the other hand, if MySQL isn’t running, it just sleeps for a second and repeats the check.

A small issue is that if, for some reason, MySQL won’t start at all, it will loop forever. If this happens, it would mean that I’ll have to manually kill that cron job, but I would have to log in anyway to see what’s wrong with MySQL. So while this method can’t support dependencies like init.d does, it does provide a good-enough solution.

Update 2012-11-23: Fixed the crontab line (it would fail when mysql was in the start/post-start state).

Django Backup Script

This is a backup script for Django projects. It’s able to automate backups of both the database and files to a local folder and a remote FTP server. It is somewhat old and has a few limitations, mainly supporting only MySQL and not supporting the new way of specifying databases introduced in Django 1.2.

It’s loosely based on my WordPress backup script and inspired the database settings auto-detection found in the newer WordPress backup script.

Usage is simple:

$ django_backup /path/to/my/proj
$ django_backup --db-only /path/to/my/proj

The latter command only backs up the database.

The script uses a few configuration variables at the top of the script to set the folder where the local backups are kept and the remote FTP server settings. The database settings are extracted directly from the settings.py of the backed-up project.
Continue reading Django Backup Script