Django and Crontab: Best Friends
May 30, 2007
For a while I know I’ve needed to figure it out, but I finally had to actually do it today. “How do I use a Django project in a standalone script?”
Thankfully, it’s quite simple.
You can use python manage.py shell to use your Django project in an interactive Python prompt, so I started looking there. Eventually I got to django/core/management.py which has a function called setup_environ that sets up the Django project environment.
from django.core.management import setup_environ
import settings
setup_environ(settings)
Put that at the top of a python script and you’re all ready. I used this today for a script that notifies users of expiring listings in a classifieds application.
Add your comment
No HTML; Only URLs and line breaks are converted.
Comments
Well spotted! That method was added exactly for this purpose, so it's pretty much part of the public API. And then apparently never properly documented.
There are other approaches (such as configuring DJANGO_SETTINGS_MODULE in your environment and then just doing normal imports), but this is the "automatic" approach.
Posted by Malcolm Tredinnick
Wow that's a lot easier than I've been doing it.
Hooray hooray! I look forward to using this, please keep up the good Django blogging.
Posted by Noah Aboussafy
This is great - one of those hidden gems which makes life so much easier.
I assume that you're running scripts from directly within your project directory? I find this a bit messy when I start to have lots of scripts stored there (it becomes difficult to differentiate between scripts and the usual modules), so usually store all standalone executables in a ./bin directory - I'd be interested to know how others organise their files...
Posted by Phil Powell
I do it with file curpath.py in bin folder with following silly code:
import sys, os
from os.path import abspath, dirname
sys.path.insert(0, dirname(dirname(dirname(abspath(__file__)))))
os.environ['DJANGO_SETTINGS_MODULE'] = 'projname.settings'
now:
import curpath
or
>>> import curpath
and you've got it.
Posted by buriy
Thanks! I was also doing this in a more "verbose" fashion.
Posted by raman
Saved my ass...
Posted by JasonH
You know you can also directly set environment variables in the crontab, right?
A lot of ours at work look like:
DJANGO_SETTINGS_MODULE=somesite.settings
0 3 * * * python /some/script.py
0 4 * * * python /some/other/script.py
DJANGO_SETTINGS_MODULE=othersite.settings
0 3 * * * python /some/script.py
0 4 * * * python /some/other/script.py
etc.
Posted by James Bennett
I like to take Jared's approach a little farther, pretty much how buriy described it. I wrote a decently robust, reusable script for automatically setting up the Django environment in standalone scripts. Check it out and download it at http://blog.capstrat.com/articles/mak...
Posted by Mike Kibbel