Login

djangopath: conveniently set sys.path and DJANGO_SETTINGS_MODULE

Author:
alia_khouri
Posted:
August 7, 2008
Language:
Python
Version:
.96
Tags:
settings path
Score:
0 (after 0 ratings)

In the past, whenever I had a script that I wanted to properly configure the settings for, I would use something like the following idiom at the top of the script:

import sys, os; dirname = os.path.dirname
# sys.path.insert(0, dirname(dirname(__file__)))
sys.path.insert(0, dirname(__file__))
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'

Notice that this is a relative setting to __file__ variable in the script. The djangopath function is an attempt to do away with the above such that I can now write the following:

from lib import djangopath; djangopath(up=2, settings='myapp.settings')

This seems to work for me, but it assumes that you are packaging your script inside your projects/apps. If they are elsewhere then you may need to resort to another method (e.g. absolute paths, etc.)

AK

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import sys, os
from os.path import dirname, abspath

def djangopath(up=1, settings=None):
    '''convenience function to easily set the application sys.path and 
       DJANGO_SETTINGS_MODULE environment variable depending on the location
       of the script file in question.
    
    :param up: how many directories up from current __file__ where the
               djangopath function is called.
    :type up: integer
    :param settings: <djangoapp>.settings
    :type: settings: string
    
    usage::
        
        >>> from lib import djangopath
        >>> djangopath(up=3, settings='myapp.settings')
        
    '''
    # here's the magic
    path = abspath(sys._getframe(1).f_code.co_filename)
    for i in range(up):
        path = dirname(path)
    sys.path.insert(0, path)
    if settings:
        os.environ['DJANGO_SETTINGS_MODULE'] = settings

More like this

  1. cron/console bootstrap django by nstrite 7 years, 6 months ago
  2. Zope testing django layer by grahamcarlyle 7 years, 1 month ago
  3. Command Line Script Launcher by dakrauth 6 years, 7 months ago
  4. Use django-admin.py instead of manage.py by whiteinge 6 years, 8 months ago
  5. Django Settings Splitter & Local Settings loader by rudude 1 year ago

Comments

Please login first before commenting.