mod_wsgi:导入同名Python模块
这是一个关于如何导入同名Python模块的后续问题,虽然这两个问题有些不相关,但我觉得还是问一个新问题比较好:
我有几个Python项目,它们都有一个叫做conf的包:
/some_folder/project_1/
conf/
__init__.py
some_source_file.py
/another_folder/project_2/
conf/
__init__.py
another_source_file.py
对于每个项目,我在site-packages文件夹里创建了一个.pth文件,内容如下:
.../site-packages/project_1.pth:
import sys; sys.path.append('/some_folder/project_1/')
.../site-packages/project_2.pth:
import sys; sys.path.append('/another_folder/project_2/')
现在,在/some_folder/project_1/这个项目里,我可以正常访问conf模块:
import conf.some_source_file
但是在/another_folder/project_2/这个项目里就不行了:
import conf.another_source_file
AttributeError: 'module' object has no attribute 'another_source_file'
这可能是因为Python在sys.path中的文件夹下只会搜索第一个conf路径。
所以,我把project_1和project_2都变成了Python包,并在其中添加了一个符号链接,这样我就可以以完全合格的方式访问这两个conf包:
/some_folder/project_1/
__init__.py
project_1 <-- symlink to .
conf/
__init__.py
some_source_file.py
/another_folder/project_2/
__init__.py
project_2 <-- symlink to .
conf/
__init__.py
another_source_file.py
在普通的Python脚本中,我现在可以从这两个conf包中导入模块:
import project_1.conf.some_source_file
import project_2.conf.another_source_file
但是,当我在使用mod_wsgi Apache模块的WSGI应用程序中尝试做同样的事情时,第二个项目的导入就失败了。具体来说,wsgi的“启动文件”(也就是在Apache配置文件中虚拟服务器的WSGIScriptAlias语句中提到的带有wsgi后缀的文件)成功导入了/another_folder/project_2/中的一个模块,而这个模块又导入了project_2/conf/another_source_file.py。
尽管/another_folder/project_2/在sys.path中,但第二次导入还是失败了。WSGI应用程序是在守护进程模式下运行的。
我该如何解决这个问题呢?
1 个回答
0
顺便说一下,这个问题在mod_wsgi的邮件列表上讨论过。根据我的记忆,问题是因为有一个模块和一个包的名字相同,导致系统选错了。