djangopath: conveniently set sys.path and DJANGO_SETTINGS_MODULE

 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. Custom mod_python AuthenHandler by aeby 5 years, 9 months ago
  2. apache authentication via cookies by sean 6 years, 2 months ago
  3. manage.py with magic python path by bikeshedder 5 years, 11 months ago
  4. Zope testing django layer by grahamcarlyle 5 years, 4 months ago
  5. TestSettingsManager: temporarily change settings for tests by carljm 4 years, 8 months ago

Comments

(Forgotten your password?)