如何在Azure虚拟机的Apache中部署使用SQL Server的Django项目?
解决Django部署到Apache时的
ImportError: No module named django.core.wsgi问题 核心原因
从错误日志可见,当前Apache加载的mod_wsgi绑定的是Python 2.7,但你的Django项目(尤其是使用django-pyodbc的场景)大概率基于Python 3开发(Django 2.0及以上版本已不再支持Python 2),导致Apache无法找到Python 3环境下的Django模块。
分步解决方案
1. 对齐Python版本与虚拟环境
- 登录Azure虚拟机,安装与本地开发一致的Python 3版本(例如Python 3.8/3.9):
sudo apt-get update && sudo apt-get install python3 python3-venv python3-pip - 进入项目目录,创建并激活独立虚拟环境:
cd /var/www/html/Agroweb python3 -m venv venv source venv/bin/activate - 在虚拟环境内重新安装所有项目依赖:
pip install -r requirements.txt # 若没有requirements.txt,手动安装核心依赖: # pip install django django-pyodbc-azure
2. 安装适配Python 3的mod_wsgi
Ubuntu默认的mod_wsgi适配Python 2,需替换为Python 3版本:
sudo apt-get install libapache2-mod-wsgi-py3 sudo a2enmod wsgi sudo systemctl restart apache2
3. 修改Apache站点配置
找到你的站点配置文件(通常位于/etc/apache2/sites-available/,例如agroweb.conf),添加虚拟环境与项目路径配置:
<VirtualHost *:80> ServerName 你的虚拟机IP或域名 # 指定虚拟环境与项目根路径 WSGIDaemonProcess agroweb python-home=/var/www/html/Agroweb/venv python-path=/var/www/html/Agroweb WSGIProcessGroup agroweb WSGIScriptAlias / /var/www/html/Agroweb/agroweb/wsgi.py # 授予wsgi.py文件访问权限 <Directory /var/www/html/Agroweb/agroweb> <Files wsgi.py> Require all granted </Files> </Directory> # 静态文件映射(可选但建议配置) Alias /static /var/www/html/Agroweb/static <Directory /var/www/html/Agroweb/static> Require all granted </Directory> </VirtualHost>
4. 修复文件权限
确保Apache用户(www-data)拥有项目目录的访问权限:
sudo chown -R www-data:www-data /var/www/html/Agroweb sudo chmod -R 755 /var/www/html/Agroweb
5. 验证配置并重启Apache
- 检查配置语法是否正确:
sudo apache2ctl configtest - 若输出
Syntax OK,重启Apache生效:sudo systemctl restart apache2
6. 适配SQL Server的额外检查
确保虚拟机安装了SQL Server ODBC驱动:
sudo apt-get install unixodbc-dev
在虚拟环境内重新安装适配性更好的SQL Server Django适配器:
pip install django-pyodbc-azure
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

