News
31st July 2015 | By:

Stand-alone Django script

Sometimes we need run a stand alone python script which uses the models of the Django project, let’s assume we want to run a python script in a cron job which uses our Django’s models and the setup is all within confide environment created with virtualenv. In order to achieve this the script needs to know several things. The first step is to add Django settings module to the environment inside the stand-alone script, this indicates the path to the Django projects and it’s ‘settings’. Then we need to activate the virtual environment within the script.

Lets assume the project layout to be the following:
Screen Shot 2015-07-31 at 10.33.25

Virtualenv

To activate the virtualenv inside the python script we need to execute a special file ‘activate_this.py’, this file automatically created inside the virtual environment. When the environment is activated all installed Python packages will become available for that script.

If you don’t know what Virtualenv is, please take a look here.
import os
import sys

# Generate path for the current standalone script
PATH=os.path.abspath(os.path.dirname(__file__))

# Setup virtual environment
if os.name == 'posix': # Unix based systems
	bin_name = 'bin'
else:                  # Windows
	bin_name = 'Scripts'

# Relative path to the virtual environment
# (relative from the stand-alone script location)
rel_path = '../venv/%s/activate_this.py' % bin_name
activate_this = os.path.join(PATH, rel_path)

# Execute script to activate virualenv
execfile(activate_this, dict(__file__=activate_this))

Django Environment

To activate Django environment we need to add the settings module to the environment path. It can be done by ‘os.environ.setdefault’.

# -*- coding: utf-8 -*-
import os
import sys

# Relative path to the Django main project folder
sys.path.append("../")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings")

If you are using Django 1.5 and lower this is all you have to do, if you are using Django 1.6 and higher an additional step is required to make this work.

import django
# Setup django internal settings, only for >= 1.6 Django
django.setup()

That’s all, we now have a fully stand alone script which can interact with our Django project.

The full copy/paste boilerplate will look like this:

import django
import os
import sys

PATH=os.path.abspath(os.path.dirname(__file__))

if os.name == 'posix': # Unix based systems
	bin_name = 'bin'
else:                  # Windows
	bin_name = 'Scripts'

# Relative path to the virtual environment
# (relative to the stand-alone script)
rel_path = '../venv/%s/activate_this.py' % bin_name
activate_this = os.path.join(PATH, rel_path)

sys.path.append("../")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings")

import django
dj_version = float(django.get_version())
if dj_version >= 1.6:
    django.setup()

# Stnd-alone script conetent ...
Tags: , , ,

2 Comments

  1. Derek
    15th October 2016 @ 10:26

    Your version check fails when there is a version number like 1.6.2.

    Suggestion:


    import django
    from distutils.version import StrictVersion
    if StrictVersion(django.get_version()) >= StrictVersion('1.6.'):
    django.setup()

    Reply
  2. Derek
    15th October 2016 @ 10:32

    There is another error: the setup() function was not added until version 1.7; so your version check needs to reflect that version and not 1.6.

    Reply

Leave a reply

Your email address will not be published. Not now, not ever. Required fields are marked *

Comments


You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Name
Email
Website

This site uses Akismet to reduce spam. Learn how your comment data is processed.