Monday, October 27, 2008

Django|python path

Setting Django Environment Variables in a Python Script

Posted: July 15, 2007
Author: Scott Newman
Category: Python, Django

When running Python programs to interact with the Django API, you don't always have the PYTHONPATH and DJANGO_SETTINGS_MODULE defined.

Before I learned this trick, I used to put my programs inside shell scripts that exported the path and settings variables before running the program. Crude, but effective.

One important thing to remember: If you're using the Django API, you must put these steps in before you try to import any Django elements (views, models, etc.)

To set environment variables:

import os

os.environ['PYTHONPATH'] = '/home/code'
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

To add locations to the search path:

import sys

sys.path.append(0, '/home/code')

You can view the search path and environment variables like this:

import sys, os

print sys.path
print os.environ.keys()

Further Reading

Dive Into Python, Chapter 2.4.1. The Import Search Path
http://www.diveintopython.org/getting_to_know_python/everything_is_an_object.html#d0e4550

Python Library Reference, Chapter 14.1.1 Process Parameters
http://docs.python.org/lib/os-procinfo.html

No comments: