uWSGI依赖问题排查:Dash应用启动失败原因咨询
问题:uWSGI运行Dash应用时出现
ModuleNotFoundError: No module named 'dash' 问题场景
目录结构
my-project/ ├─ src/ │ ├─ app.py │ ├─ wsgi.py ├─ venv/ ├─ requirements.txt
核心代码
app.py
from dash import Dash, html, dcc import plotly.express as px import pandas as pd app = Dash(__name__) server = app.server df = pd.DataFrame({ "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"], "Amount": [4, 1, 2, 2, 4, 5], "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"] }) fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group") app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for your data. '''), dcc.Graph( id='example-graph', figure=fig ) ]) if __name__ == '__main__': app.run_server(debug=False)
wsgi.py
from app import server as application if __name__ == '__main__': application.run()
可正常运行的操作
激活虚拟环境后,执行以下命令应用可正常加载:
python3 src/app.py
python3 src/wsgi.py
出错操作及错误信息
进入src目录执行uWSGI测试命令:
uwsgi --socket 0.0.0.0:5000 --protocol=http -w wsgi:application
触发错误:
*** Operational MODE: single process *** Traceback (most recent call last): File "./wsgi.py", line 1, in <module> from app import server as application File "./app.py", line 1, in <module> from dash import Dash, html, dcc ModuleNotFoundError: No module named 'dash' unable to load app 0 (mountpoint='') (callable not found or import error)
已尝试在src目录添加__init__.py,问题未解决。
原因分析
- uWSGI未关联虚拟环境:即使激活了虚拟环境,uWSGI默认不会自动使用虚拟环境的Python解释器和依赖包,可能调用了系统全局Python(未安装dash)。
- 模块搜索路径问题:从项目根目录运行
python3 src/app.py时,Python会自动将src目录加入sys.path;但进入src目录运行uWSGI时,sys.path的根路径变为src,虚拟环境的依赖不在搜索范围内,且未明确指定项目根路径。
解决方案
方案1:明确指定虚拟环境与项目路径运行uWSGI
从项目根目录执行命令(无需进入src),直接关联虚拟环境并添加项目路径:
uwsgi --socket 0.0.0.0:5000 --protocol=http -w src.wsgi:application --pythonpath $(pwd) --venv $(pwd)/venv
--pythonpath $(pwd):将项目根目录加入Python模块搜索路径--venv $(pwd)/venv:指定uWSGI使用当前虚拟环境
方案2:修改wsgi.py添加项目根路径
修改src/wsgi.py,在导入模块前手动将项目根目录加入sys.path:
import sys from pathlib import Path # 获取项目根目录(src的父目录) project_root = Path(__file__).parent.parent sys.path.append(str(project_root)) from app import server as application if __name__ == '__main__': application.run()
之后使用虚拟环境内的uWSGI在src目录执行命令:
../venv/bin/uwsgi --socket 0.0.0.0:5000 --protocol=http -w wsgi:application
方案3:确保uWSGI安装在虚拟环境内
激活虚拟环境后安装uWSGI:
pip install uwsgi
从项目根目录执行uWSGI命令,此时uWSGI会自动读取虚拟环境的依赖:
uwsgi --socket 0.0.0.0:5000 --protocol=http -w src.wsgi:application --pythonpath $(pwd)
内容的提问来源于stack exchange,提问作者DougM
相关产品推荐
相关产品推荐

