0

In my home directory, I have a folder called local. In it, there are files called __init__.py and local_settings.py. My django app is in a completely different directory. When the app is NOT running in DEBUG mode, I want it to load the local_settings.py file. How can this be acheived? I read the below:

Import a module from a relative path

Importing files from different folder in Python

http://docs.python.org/tutorial/modules.html

Basically, those tutorials are allowing to import from another directory, but what about a completely different working tree? I don't want to keep doing .., .., .. etc. Is there a way to goto the home directory?

I tried the following code:

import os, sys
os.chdir(os.path.join(os.getenv("HOME"), 'local'))
from local_settings import *

But i keep seeing errors in my apache error.log for it...

Community
  • 1
  • 1
KVISH
  • 12,923
  • 17
  • 86
  • 162
  • 1
    It would be better if you make the settings file in the same directory and specify it when you run the app. – Srinivas Reddy Thatiparthy Sep 03 '12 at 18:26
  • I could..problem is that for deployment, these are local settings, not something I want on the source control. When I do a deployment, these would be overwritten or removed. – KVISH Sep 03 '12 at 18:33

2 Answers2

0

os.chdir just affects the current working directory, which has nothing whatsoever to do with where Python imports modules from.

What you need to do is to add the the local directory to the Pythonpath. You can either do this from the shell by modifying PYTHONPATH, or from inside Python by modifying sys.path:

import sys
import os
sys.path.append(os.path.expanduser("~/local"))
import local_settings
binarybelle
  • 71
  • 1
  • 9
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

In response to your concerns about source control, you can just set the source control to ignore that file, and/or have a symlink installed as part of your deploy script to link the file on the os into another. I do both , though not in django. but it's a trivial task.

your deploy layout could look like this:

/current ( symlink to /releases/v3 )
/settings/local_settings.py
/releases/v1
/releases/v2
/releases/v3

and a task runs as part of your deploy:

cd /current 
ln -s /settings/local_settings.py local_settings.py

if you're deploying with fab or capistrano, it's a few lines of configuration. i'm sure you could do this with puppet/chef simply too.

Jonathan Vanasco
  • 15,111
  • 10
  • 48
  • 72