Skip to main content
 首页 » 编程设计

python之使用 WSGI、Flask 和 Apache 导入错误

2024年08月29日32落叶无声

对基于 python 的网络应用程序完全陌生,所以我有点迷路了。这是我的 apache 错误:

[Wed May 08 22:41:47 2013] [error] [client 64.56.91.45] mod_wsgi (pid=23704): Target WSGI script '/home/http/public/hello/hello.wsgi' cannot be loaded as Python module. 
[Wed May 08 22:41:47 2013] [error] [client 64.56.91.45] mod_wsgi (pid=23704): Exception occurred processing WSGI script '/home/http/public/hello/hello.wsgi'. 
[Wed May 08 22:41:47 2013] [error] [client 64.56.91.45] Traceback (most recent call last): 
[Wed May 08 22:41:47 2013] [error] [client 64.56.91.45]   File "/home/http/public/hello/hello.wsgi", line 3, in <module> 
[Wed May 08 22:41:47 2013] [error] [client 64.56.91.45]     from hello import app as application 
[Wed May 08 22:41:47 2013] [error] [client 64.56.91.45]   File "/home/http/public/hello/hello.py", line 1, in <module> 
[Wed May 08 22:41:47 2013] [error] [client 64.56.91.45]     from flask import Flask 
[Wed May 08 22:41:47 2013] [error] [client 64.56.91.45] ImportError: No module named 'flask' 
[Wed May 08 22:41:47 2013] [error] [client 64.56.91.45] File does not exist: /home/http/public/favicon.ico 

显然,它找不到flask 模块。我查了一下,似乎大多数人都是通过将项目目录附加到路径来让它工作的,就像这样:(hello.wsgi)

import sys 
sys.path.insert(0, "/home/http/public/hello") 
from hello import app as application 

这里是 hello.py:

from flask import Flask 
app = Flask(__name__) 
 
@app.route('/') 
def hello_world(): 
    return 'Hello World!' 
 
if __name__ == '__main__': 
    app.run(host='0.0.0.0') 

当作为 python hello.py 运行时效果很好,但是,当浏览到 host/hello 时会抛出 500 错误。这是 Apache 配置:

WSGIDaemonProcess hello user=http group=http threads=5 
WSGIScriptAlias /hello "/home/http/public/hello/hello.wsgi" 
 
<Directory /home/http/public/hello/> 
    WSGIProcessGroup hello 
    WSGIApplicationGroup %{GLOBAL} 
    Order deny,allow 
    Allow from all 
</Directory> 

我有点迷路了。

请您参考如下方法:

mod_wsgi 模块是针对特定的 Python 版本构建的,并且只能与该版本一起使用。您不能强制它使用不同的版本。因此,如果您安装了多个版本,则需要确保您正在安装包并针对同一版本在开发中运行代码。

您可以通过运行测试来确定 mod_wsgi 使用的是哪个 Python 版本/安装: