You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

CentOS7部署Flask遇WSGI加载失败:默认用Python2.7而非虚拟环境版本

解决CentOS7上Apache+mod_wsgi部署Flask的两个问题

咱们先逐个解决你的问题,这两个问题其实存在关联,先搞定Python版本的问题,模块加载失败的情况也会跟着改善。

一、修正WSGI使用Python2.7而非虚拟环境版本的问题

你的虚拟主机配置里的WSGIDaemonProcess参数写错了,这是核心原因:

  • 你当前配置的python-home=/home/nmapi:home/nmapi/deps/venv/lib/python3.5有两处错误:
    1. 第二个路径home/nmapi/...没有以/开头,属于相对路径,Apache无法正确识别
    2. python-home只需要直接指向虚拟环境的根目录即可,不需要指定到lib/python3.5层级;而且你这里写的虚拟环境路径和app.wsgi里的/home/nmapi/venv不一致,必须统一

另外要注意:如果是用系统默认yum安装的mod_wsgi,它是绑定Python2.7编译的,这种情况下即使指定虚拟环境也会失效,需要重新安装对应Python3的mod_wsgi:

  1. 先卸载系统自带的mod_wsgi:
    yum remove mod_wsgi
    
  2. 激活虚拟环境并安装mod_wsgi,然后配置Apache加载:
    source /home/nmapi/venv/bin/activate
    pip install mod_wsgi
    mod_wsgi-express module-config
    
    把输出的三行配置(LoadModuleWSGIPythonHomeWSGIPythonPath)添加到Apache的配置文件(比如/etc/httpd/conf.d/wsgi.conf)中

最后修正虚拟主机里的WSGIDaemonProcess配置:

WSGIDaemonProcess score threads=5 python-home=/home/nmapi/venv

二、解决"WSGI脚本无法加载为Python模块"的问题

你的app.wsgi里有几处明显错误,逐一修正:

  1. 路径错误sys.path.insert(0,"home/nmapi/project/dir")是相对路径,必须改成绝对路径:
    sys.path.insert(0,"/home/nmapi/project/dir")
    
  2. activate_this代码格式问题:你把代码写在一行容易出现语法错误,改成标准写法:
    activate_this = '/home/nmapi/venv/bin/activate_this.py'
    with open(activate_this) as file_:
        exec(file_.read(), dict(__file__=activate_this))
    
  3. 缺少WSGI入口对象:Flask应用需要向WSGI服务器暴露application对象,假设你的run.py里Flask实例是app = Flask(__name__),那要修改导入语句:
    from run import app as application
    
  4. 日志优化:调高日志级别方便排查问题:
    logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
    

修正后的完整app.wsgi如下:

activate_this = '/home/nmapi/venv/bin/activate_this.py'
with open(activate_this) as file_:
    exec(file_.read(), dict(__file__=activate_this))

# Expand Python classes path with your app's path
from werkzeug.wsgi import DispatcherMiddleware
import sys
import logging

print(sys.path)
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
sys.path.insert(0,"/home/nmapi/project/dir")

from run import app as application

另外注意:你的虚拟主机配置里WSGIScriptAlias指向的是datascience.wsgi,但报错里的脚本是app.wsgi,路径不一致,要改成正确的路径:

WSGIScriptAlias /test_wsgi /home/nmapi/project/dir/app.wsgi

最后重启Apache服务让配置生效:

systemctl restart httpd

如果还是有问题,可以查看Apache的错误日志(logs/error.log/var/log/httpd/error_log),里面会有更详细的报错信息,方便进一步排查。

内容的提问来源于stack exchange,提问作者ranjith d

火山引擎 最新活动