【问题标题】:WSGI: ImportError: No module named hello (module in the same directory of the main .py file)WSGI: ImportError: No module named hello (module in the same directory of the main .py file)
【发布时间】:2019-11-28 11:37:41
【问题描述】:

这不是 Apache with virtualenv and mod_wsgi : ImportError : No module named 'django' 的重复,因为我在这里使用任何 virtualenv,而且我试图导入另一个框架的模块(例如作为django),但只是一个模块在同一目录中


这是我的设置:

/var/www/test/app.py:

import os, time, sys
from bottle import route, run, template, default_app

os.chdir(os.path.dirname(os.path.abspath(__file__)))

import hello

@route('/')
def index():
    return 'Hello world Python ' + sys.version

application = default_app()

/var/www/test/hello.py:

# just an example module
def test():
    print 'hello'

Apache 配置:

<VirtualHost *:80>
  ServerName example.com
  <Directory />
    Require all granted
  </Directory>
  WSGIScriptAlias / /var/www/test/app.py
  WSGIDaemonProcess test user=www-data group=www-data processes=5 threads=5 display-name=test python-path=/var/www/test/
</VirtualHost>

然后我得到:

ImportError: 没有名为 hello 的模块

什么不正确? WSGIDaemonProcess ... python-path=/var/www/test/不应该帮助模块hello被加载吗?

【问题讨论】:

    标签: python apache mod-wsgi wsgi


    【解决方案1】:

    Apache 不会切换到当前工作目录,因此它不会在你想的地方搜索 hello。

    您可以通过以下方式更改 app.py。

    import os, time, sys
    from bottle import route, run, template, default_ap
    # add the scripts directory to the python path so that hello can be found
    sys.path.insert(0, os.path.realpath(os.path.dirname(__file__)))
    

    优点是您不必弄乱 apache 配置文件

    【讨论】:

    • 感谢您的回答。但是我已经在app.py:os.chdir(os.path.dirname(os.path.abspath(__file__))) 中这样做了,为什么这还不够?
    • 从 python 中更改目录不起作用。它只是更改了工作目录,但不再更改 pythonpath。您必须更改 pythonpath (sys.path)
    • 哦,好吧,PYTHONPATH 不同,你是对的。
    • sys.path 是 python 中的变量,它结合了环境变量 PYTHONPATH 的内容和其他一些自动确定的值所以 sys.path.insert(0, "path_to_add") 应该完成这项工作
    • 谢谢!但是,看看我在问题中的初始配置,我已经将它附加到 WSGI 配置中:python-path=/var/www/test/,为什么它不能使用它?这很奇怪,你不这么认为吗?参数WSGIDaemonProcess ... python-path=... 应该正是为此,但这里似乎没有考虑到如果没有给出WSGIScriptAlias ... process-group=......
    【解决方案2】:

    解决办法是:

    • 确实有WSGIDaemonProcess ... python-path=...

    • 还有一个WSGIScriptAlias ... process-group=...(不知道为什么这个process-group参数与允许或不从同一目录加载模块相关联,但它有效!)

    例子:

    WSGIScriptAlias / /var/www/test/app.py process-group=test
    WSGIDaemonProcess test user=www-data group=www-data processes=5 threads=5 display-name=test python-path=/var/www/test/
    

    另请参阅:https://bottlepy.org/docs/dev/deployment.html#apache-mod-wsgi

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 2016-12-23
      • 2016-12-19
      • 2018-05-21
      • 1970-01-01
      • 2015-09-10
      • 1970-01-01
      相关资源
      最近更新 更多