31st July 2015 | By: marcinkawa
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.
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.
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))
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 ...