Apache部署Flask应用遇mod_wsgi模块找不到错误求助
问题诊断
错误日志明确显示ModuleNotFoundError: No module named 'app',结合你的配置,主要存在以下几个问题:
1. init.py代码缩进错误
你在激活虚拟环境的with语句后,所有Flask相关的导入和函数定义都缩进了,这会导致这些代码被限制在with的局部作用域内,外部无法识别app模块的内容。
2. WSGI文件导入错误
你的app.wsgi试图导入from app import main as application,但main是蓝图对象,不是Flask的WSGI应用实例,无法作为WSGI入口使用。
3. 虚拟环境激活位置不合理
在__init__.py里激活虚拟环境容易引发作用域问题,应该在WSGI文件中统一处理。
修复步骤
步骤1:修正__init__.py的缩进
把with语句之后的所有代码顶格,取消多余缩进:
activate_this_file = "/var/www/bdl/auth/bin/activate_this.py" with open(activate_this_file) as _file: exec(_file.read(), dict(__file__=activate_this_file)) from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager # init SQLAlchemy so we can use it later in our models db = SQLAlchemy() def create_app(): app = Flask(__name__) app.config['SECRET_KEY'] = 'xxxxxxxxxxxxxxxxx' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' db.init_app(app) login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.init_app(app) from .models import User @login_manager.user_loader def load_user(user_id): # since the user_id is just the primary key of our user table, use it in the query for the user return User.query.get(int(user_id)) # blueprint for auth routes in our app from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) # blueprint for non-auth parts of app from .main import main as main_blueprint app.register_blueprint(main_blueprint) from . import models with app.app_context(): db.create_all() return app
步骤2:修改app.wsgi文件
调整导入逻辑,正确初始化Flask应用作为WSGI入口:
import sys sys.path.insert(0, "/var/www/bdl/portal") # 激活虚拟环境 activate_this = '/var/www/bdl/auth/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) from app import create_app application = create_app()
步骤3:修复文件权限
确保Apache运行用户(通常为www-data)对应用目录及文件有读取权限:
sudo chown -R www-data:www-data /var/www/bdl/portal sudo chmod -R 755 /var/www/bdl/portal
步骤4:重启Apache服务
让配置修改生效:
sudo systemctl restart apache2
额外验证点
- 确认
/var/www/bdl/portal目录下存在__init__.py、main.py、auth.py、models.py等所有本地运行时的必要文件。 - 进入虚拟环境执行
pip list,确认已安装Flask、Flask-SQLAlchemy、Flask-Login等依赖。
内容的提问来源于stack exchange,提问作者Carlos Marcano
相关产品推荐
相关产品推荐

