这是这个问题的“现代”答案。我成功地在生产 Ubuntu 16.04 服务器上部署了 Django 1.11,该服务器连接到在另一台服务器上运行的 MS SQL Server 2017。
首先,安装原生MS ODBC驱动“ODBC Driver 17 for SQL Server”:
# https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server#ubuntu-1404-1604-and-1710
sudo su
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
apt-get update
ACCEPT_EULA=Y apt-get install msodbcsql
apt-get install unixodbc-dev
# test you can actually get to port 1433 on the server that is running MS SQL:
nc -z -v -w5 host.where.sql.server.is.running.com 1433
# add /opt/mssql-tools/bin to your PATH in .bash_profile, e.g.:
# PATH="$HOME/bin:$HOME/.local/bin:/opt/mssql-tools/bin:$PATH"
# source ~/.bash_profile
# now, test that you can actually connect to MS SQL Server:
sqlcmd -S host.where.sql.server.is.running.com -U db_username -P db_password
其次,确保你pip install这些模块:
# https://github.com/michiya/django-pyodbc-azure
django-pyodbc-azure==1.11.9.0
# https://github.com/mkleehammer/pyodbc/wiki
pyodbc==4.0.22
三、修改你的Djangosettings.py的DATABASES条目:
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'db_name',
'USER': 'db_username',
'PASSWORD': 'db_password',
'HOST': 'host.where.sql.server.is.running.com',
'PORT': '1433',
'OPTIONS': {
'driver': 'ODBC Driver 17 for SQL Server',
'isolation_level': 'READ UNCOMMITTED', # prevent SELECT deadlocks
},
},
}
我省略了我的其余配置(nginx、Gunicorn、Django REST 框架等),但这超出了此答案的范围。
更新:这已经在生产环境中运行了 6 个多月,并且当多个连接在同一个表上执行 SELECT 查询时,除了 MS SQL Server 特定的死锁之外没有任何问题,这已通过 isolation_level 修复环境。该系统每天有大约 2000 个新用户。