Cron a Django Program


One of the issue I faced while developing a website in Django was I always had a script which collects or data which is to be in the cron. But Django usually needs a lot of configurations and settings for the environment to run. So after some searches I got that django has an undocumented API of settings which we would use of the same. So here is a file which you could include for any file you would like to run as cron and this file would do the rest.


import os, sys, re

top_level_rx = re.compile(r'^(/|[a-zA-Z]:\)$')
def is_top_level(path):
return top_level_rx.match(path) is not None

def prepare_environment():
# we'll need this script's directory for searching purposess
curdir, curfile = os.path.split(os.path.abspath(__file__))

# move up one directory at a time from this script's
# path, searching for settings.py
settings_module = None
while not settings_module:
try:
sys.path.append(curdir)
settings_module = __import__('settings', {}, {}, [''])
sys.path.pop()
break
except ImportError:
settings_module = None

# have we reached the top-level directory?
if is_top_level(curdir):
raise Exception("settings.py was not found in the script's directory or any of its parent directories.")

# move up a directory
curdir = os.path.normpath(os.path.join(curdir, '..'))

# set up the environment using the settings module
from django.core.management import setup_environ
setup_environ(settings_module)

prepare_environment()

Lets name this file as cron_settings.py . So each script which is to be inserted in cron can include this file as


import cron_settings

And they should be good to run as cron.

There is also another method which I used to use. I moved from this method as it used to have the paths hard coded so it wasn’t portable but here it is:


import django
import os
import sys

sys.path += ['/usr/bin/python']
sys.path += ['<Django  Folder>']
sys.path += ['<Django Project Path>']
os.environ['DJANGO_SETTINGS_MODULE'] = '<DjangoProject>.settings'

Well both works. So you could use the one which suits you more.


, , , ,

  1. No comments yet.
(will not be published)