【问题标题】:Load module into apache + mod-wsgi将模块加载到 apache + mod-wsgi
【发布时间】:2010-11-12 07:48:03
【问题描述】:

我正在使用 Apache + mod-wsgi。

在我的 httpd.conf 中,文件末尾有以下附加行。

LoadModule wsgi_module modules/mod_wsgi-win32-ap22py27-3.3.so
WSGIScriptAlias / "C:/Projects/Folder/web/"
<Directory "C:/Projects/Folder/web">
AllowOverride None
Options None
Order deny,allow
Allow from all
</Directory>

当我通过http://localhost/script/index.py在Windows中执行以下index.py脚本时

def application(environ, start_response):
    status = '200 OK' 
    output = 'Hello World!'
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    return [output]

效果很好。

但是,当我在index.py 的第一行添加import utils 时,我得到了

ImportError: No module named utils

utils.pyindex.py 是同一目录

我需要设置什么额外的配置吗?

我尝试了@dan_waterworth 给出的建议

import sys, os
sys.path.append(os.path.dirname(__file__))

通过导入我自己的模块,我不再出现错误。但是,当我通过 easy_install 导入正在安装的模块时,会发生错误。

   File "C:/Projects/Folder/web/script\\connection.py", line 1, in <module>
     import psycopg2
   File "build\\bdist.win32\\egg\\psycopg2\\__init__.py", line 65, in <module>
     from psycopg2 import tz
 ImportError: cannot import name tz

import psycopg2 执行没有问题,如果此脚本作为独立应用程序执行。

【问题讨论】:

    标签: python apache mod-wsgi


    【解决方案1】:

    我发现我必须添加几行来附加 python 路径。比如:

    import sys, os
    sys.path.append(os.path.dirname(__file__))
    
    import utils
    

    对于第二部分,只需为您的导入目录添加额外的行。即:

    sys.path.append([enter path here])
    

    要查找您的导入目录,请在交互式 python 提示符中键入:

    import sys
    print sys.path
    

    【讨论】:

    • 11 秒前,更广泛和更通用的解决方案 :) +1
    • 我得到 NameError: name 'os' is not defined
    • 对不起,我忘记在导入中添加os,现在试试
    • @dan_waterworth,谢谢。有改善。但是,当我尝试导入通过 easy_install 安装的模块时出现错误。我更新了我的问题。
    【解决方案2】:

    其他答案的重点是让脚本本身破坏它自己的 PYTHONPATH。另一种方法是找出正确的 Apache 设置,以便为 Python 和 WSGI 应用程序设置可行的路径。

    我的 conf 文件中有这些:

    PassEnv PYTHONPATH
    WSGIPythonHome  C:/Python/Python26
    WSGIPythonPath  C:/Python/Python26;C:/myproject/PyLib
    

    如果你不想通过环境的 PYTHONPATH,我认为你可以使用:

    SetEnv PYTHONPATH C:/your/paths/go/here;C:/and/here
    

    我建议你试一试。

    【讨论】:

      【解决方案3】:

      sys.pathsys.modules 检查该目录是否实际添加为模块目录。如果不是sys.path.append它。

      【讨论】:

      • 其实没必要检查。 Python 只会使用第一个有效的,如果有重复,它最多会浪费一小部分时间,而且代码更容易阅读。
      • 我的意思是让他分析情况。也许该目录实际上首先存在于sys.path 中,问题不在于导入。否则谢谢。
      猜你喜欢
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 2015-11-13
      • 2021-11-10
      • 2018-01-18
      • 1970-01-01
      相关资源
      最近更新 更多