导入不同的Django项目设置

时间:2014-10-20 05:12:47

标签: python django import settings

我正在尝试从同一个python模块导入不同的Django项目设置文件。

project_path = ["/home/Desktop/test1", "/home/Desktop/test2", "/home/Desktop/test3"]
for j, i in enumerate(project_path):
    if os.path.exists(i):
        sys.path.append(i)
        os.system("fm -rf " + project_path[j - 1] + "/settings.pyc")
        import settings
        print "settings file path>>>", settings.__file__
        project_directory = os.path.dirname(settings.__file__)
        print "Application direcotry>>>", project_directory
        project_name = os.path.basename(project_directory)
        print "Application name>>>", project_name
        sys.path.append(os.path.join(project_directory, '..'))
        project_module = __import__(project_name, '', '', [''])
        # Set DJANGO_SETTINGS_MODULE appropriately.
        sys.path.remove(i)

我得到以下结果:

settings file path>>> home/Desktop/test1/settings.pyc
Application direcotry>>> home/Desktop/test1
Application name>>> test1
settings file path>>> home/Desktop/test1/settings.pyc
Application direcotry>>> home/Desktop/test1
Application name>>> test1
settings file path>>> home/Desktop/test1/settings.pyc
Application direcotry>>> home/Desktop/test1
Application name>>> test1

我的问题是,即使我删除项目路径并添加新路径,然后它也导入相同的应用程序路径。所以我无法导入下一个应用程序路径。

我甚至尝试重新加载设置文件。

import settings
settings = reload(settings) 

1 个答案:

答案 0 :(得分:0)

尝试使用包名称导入并注释不相关的行。 确保文件夹test1 / test2 / test3首先是包。如果没有,请在文件夹中添加__init__.py

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys

project_path = ["/home/Desktop/test1", "/home/Desktop/test2", "/home/Desktop/test3"]

for path in project_path:

    sys.path.append(path)
    package_name = path.split('/')[2]

    cmd = 'import ' + package_name + '.settings'
    sys.path.remove(path)