Using Sql Server with Django in production

前端 未结 6 640
醉话见心
醉话见心 2020-12-04 10:54

Has anybody got recent experience with deploying a Django application with an SQL Server database back end? Our workplace is heavily invested in SQL Server and will not supp

6条回答
  •  广开言路
    2020-12-04 11:34

    Here's a "modern" answer to this question. I successfully deployed Django 1.11 on a production Ubuntu 16.04 server that connects to MS SQL Server 2017 running on another server.

    First, install the native MS ODBC driver "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
    

    Second, make sure you pip install these modules:

    # https://github.com/michiya/django-pyodbc-azure
    django-pyodbc-azure==1.11.9.0
    
    # https://github.com/mkleehammer/pyodbc/wiki
    pyodbc==4.0.22
    

    Third, modify the DATABASES entry of your Django settings.py:

    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
            },
        },
    }
    

    I'm omitting the rest of my configuration (nginx, Gunicorn, Django REST Framework, etc), but that's outside the scope of this answer.

    Update: this has been running in production for 6+ months now and hasn't had any issues beyond MS SQL Server-specific deadlocks when multiple connections are doing SELECT queries on the same table, which was fixed with the isolation_level setting. The system gets about 2k new users every day.

提交回复
热议问题