Login

djangopath: conveniently set sys.path and DJANGO_SETTINGS_MODULE

Author:
alia_khouri
Posted:
August 7, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.