{"id":13775021,"url":"https://github.com/azure-samples/azure-sql-db-django","last_synced_at":"2025-05-11T07:31:48.273Z","repository":{"id":44553231,"uuid":"450480630","full_name":"Azure-Samples/azure-sql-db-django","owner":"Azure-Samples","description":"REST API using Python, Django, Azure SQL DB \u0026 mssql-django driver","archived":false,"fork":false,"pushed_at":"2024-08-06T19:07:53.000Z","size":61,"stargazers_count":28,"open_issues_count":0,"forks_count":31,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-11-07T10:43:56.042Z","etag":null,"topics":["azure-sql","django","django-rest-framework","mssql-django","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Azure-Samples.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-01-21T12:20:08.000Z","updated_at":"2024-09-21T01:52:32.000Z","dependencies_parsed_at":"2024-06-24T14:24:41.071Z","dependency_job_id":null,"html_url":"https://github.com/Azure-Samples/azure-sql-db-django","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Fazure-sql-db-django","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Fazure-sql-db-django/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Fazure-sql-db-django/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Azure-Samples%2Fazure-sql-db-django/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Azure-Samples","download_url":"https://codeload.github.com/Azure-Samples/azure-sql-db-django/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224708955,"owners_count":17356521,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["azure-sql","django","django-rest-framework","mssql-django","python"],"created_at":"2024-08-03T17:01:32.861Z","updated_at":"2024-11-17T10:30:26.524Z","avatar_url":"https://github.com/Azure-Samples.png","language":"Python","funding_links":[],"categories":["Code Samples"],"sub_categories":["REST"],"readme":"---\npage_type: sample\nlanguages:\n- python\n- sql\nproducts:\n- vs-code\n- azure-sql-database\n\ndescription: \"Creating REST API with Python, Django and Azure SQL\"\nurlFragment: \"azure-sql-db-django\"\n---\n\n# Creating REST API with Python, Django and Azure SQL\n\n[![License](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/azure-samples/azure-sql-db-django/blob/main/LICENSE)\n\nThe sample uses the [Django](https://www.djangoproject.com/) web framework and [Django Rest framework](https://www.django-rest-framework.org/) package to easily implement REST APIs. [mssql-django](https://github.com/microsoft/mssql-django) v1.1 used to establish database connectivity with Azure SQL.\n\n\u003e [!NOTE]\n\u003e [mssql-django](https://github.com/microsoft/mssql-django) is a fork of [django-mssql-backend](https://pypi.org/project/django-mssql-backend/). This driver provides an enterprise database connectivity option for the Django Web Framework, with support for Microsoft SQL Server and Azure SQL Database.\n\u003e [mssql-django](https://github.com/microsoft/mssql-django) supports Django 2.2, 3.0, 3.1, 3.2 and 4.0.\n\n## Download the sample code\n\nClone this repository:\n\n```bash\ngit clone https://github.com/azure-samples/azure-sql-db-django\n```\n\nAlternatively you can clone the code using Visual Studio Code as well.\n\n- Open the folder location where you want to clone the code\n- In Visual Studio Code, select Source Control \u003e ... \u003e Clone (or select View, Command Palette and enter Git:Clone), paste the [Git repository URL](https://github.com/azure-samples/azure-sql-db-django.git), and then select Enter\u003c/\u003e.\n\nOnce you have the code downloaded to your local computer. You should see folder structure as below:\n\n```properties\nazure-sql-db-django\n ┣ customerapi\n ┃ ┣ migrations\n ┃ ┣ admin.py\n ┃ ┣ apps.py\n ┃ ┣ models.py\n ┃ ┣ serializers.py\n ┃ ┣ tests.py\n ┃ ┣ urls.py\n ┃ ┣ views.py\n ┃ ┗ __init__.py\n ┣ django-sql-project\n ┃ ┣ asgi.py\n ┃ ┣ settings.py\n ┃ ┣ urls.py\n ┃ ┣ wsgi.py\n ┃ ┗ __init__.py\n ┣ LICENSE\n ┣ manage.py\n ┣ README.md\n ┗ requirements.txt\n```\n\n## Create Azure SQL Database\n\nIf you don't have an Azure SQL server already, you can create one (no additional costs for a server) by running the following [AZ CLI](https://docs.microsoft.com/en-us/cli/azure/) command (via [WSL](https://docs.microsoft.com/en-us/windows/wsl/), or Linux or [Azure Cloud Shell](https://azure.microsoft.com/en-us/features/cloud-shell/)):\n\nCreate a resource group if you don't have one already created:\n\n```azurecli-interactive\naz group create -l \u003clocation\u003e -n \u003cMyResourceGroup\u003e\n```\n\nCreate the Database Server:\n\n```azurecli-interactive\naz sql server create -n \u003cserver-name\u003e -l \u003clocation\u003e --admin-user \u003cadmin-user\u003e --admin-password \u003cadmin-password\u003e -g \u003cresource-group\u003e\n```\n\n\u003e [!NOTE]\n\u003e Make sure to note the database name, username and password somewhere safe.\n\nCreate a new Azure SQL database:\n\n```azurecli-interactive\naz sql db create -g \u003cresource-group\u003e -s \u003cserver-name\u003e -n my-db --service-objective GP_Gen5_2\n```\n\nMake sure you have the firewall configured to allow your machine to access Azure SQL:\n\n```azurecli-interactive\naz sql server firewall-rule create --resource-group \u003cresource-group\u003e --server \u003cserver-name\u003e --name AllowMyClientIP_1 --start-ip-address \u003cyour_public_ip\u003e --end-ip-address \u003cyour_public_ip\u003e\n```\n\nYou can get your public IP [here](https://ipinfo.io/ip) or through other ways, for example: https://ifconfig.me/\n\n## Setup the local environment\n\nMake sure you have [Python](https://www.python.org/) =\u003e 3.8.10 installed on your machine.\n\nTo confirm you can run `python` or `python3` on terminal.\n\n```python\npython --version\n```\n\n\u003e [!NOTE]\n\u003eAll the commands shown here are for Windows. If you are working on any other OS/ environment e.g. Linux, MAC etc. change these commands accordingly.\n\nMake sure you have [venv](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/) installed and create a new virtual environment in the folder where you have cloned the repository:\n\n```bash\npython -m venv env\n```\n\n\u003e [!NOTE]\n\u003e In the above command the second parameter `env` is the location to create virtual environment.\\\n\u003e `venv` will create a virtual Python installation in the `env` folder.\\\n\u003e You should exclude your virtual environment directory from your version control system using `.gitignore` or similar.\n\nBefore you start installing or using django packages in your virtual environment, you'll need to [activate it](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/#activating-a-virtual-environment), for example on Windows:\n\n```bash\n.\\env\\Scripts\\activate\n```\n\n\u003e [!NOTE]\n\u003e You can confirm, you’re in the virtual environment by checking the location of your Python interpreter. It should be in the `env` directory.\n\u003e\n\u003e ```python\n\u003e where python\n\u003e ```\n\u003e\n\u003e As long as your virtual environment is activated, `pip` will install packages into that specific environment and you’ll be able to import and use packages in your Python application.\n\n## Install the dependencies\n\nMake sure virtual environment is active and you are into your `\u003cworking_folder\u003e\\azure-sql-db-django`.\n\n\u003e [!TIP]\n\u003e You can install all the required packages in one go by running the below command and directly move to Database ConnectionString **Configuration** section or may follow the instructions to execute them one by one:\n\u003e\n\u003e ```python\n\u003e pip install -r .\\requirements.txt\n\u003e ```\n\nInstall [Django](https://www.djangoproject.com/download/):\n\n```python\npip install django\n```\n\nAlso, install [Django REST framework](hhttps://www.django-rest-framework.org/#installation) for REST API:\n\n```python\npip install djangorestframework\n```\n\nYou should also install [django-cors-headers](https://pypi.org/project/django-cors-headers/). It's a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS).\n\n```python\npip install django-cors-headers\n```\n\n\u003e [!NOTE]\n\u003e Adding [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) headers allows your resources to be accessed on other domains. It’s important you understand the implications before adding the headers since you could be unintentionally opening up your site’s private data to others.\n\n## Configure Azure SQL connectivity with Django App\n\n### Dependencies\n\n- pyodbc 3.0 or newer\n- Microsoft SQL Server ODBC driver\n\n### Installation\n\n- Install ODBC driver: [Instructions](https://docs.microsoft.com/en-us/sql/connect/odbc/microsoft-odbc-driver-for-sql-server?view=sql-server-ver15)\n\n- Install pyodbc:\n\n    ```python\n    pip install pyodbc\n    ```\n\n- Install mssql-django:\n\n    ```python\n    pip install mssql-django\n    ```\n\n### Configuration\n\nConfigure the Database ConnectionString in the `settings.py` file used by your Django project to use `mssql` and the related ODBC driver.\n\n```sql\nDATABASES = {\n    'default': {\n        'ENGINE': 'mssql',\n        'PORT': '1433',\n        'OPTIONS': {\n                'driver': 'ODBC Driver 17 for SQL Server',\n            },\n    }\n}\n```\n\nTo connect Azure SQL DB using MSI (Managed Service Identity), you can have settings as below:\n\n```sql\nDATABASES = {\n    'default': {\n         'ENGINE': 'mssql',\n         'Trusted_Connection': 'no', \n         'OPTIONS': { \n             'driver': 'ODBC Driver 17 for SQL Server', \n             'extra_params': \"Authentication=ActiveDirectoryMsi;Encrypt=yes;TrustServerCertificate=no\" }\n     }\n}\n```\n\nPlease note that for this sample we decided to avoid having secrets in the `settings.py` file. All sensitive details will be loaded from environment variables. For development purposes you can create an `.env` file, using the provided `.env.sample`, to provide database connection info.\n\n\u003e [!WARNING]\n\u003e [mssql-django](https://github.com/microsoft/mssql-django) doesn't support using time zones yet, so the recommendation is to ensure the `USE_TZ` option is set to `False`.\n\u003e\n\u003e```sql\n\u003e\n\u003e DATABASES = {\n\u003e ...\n\u003e }\n\u003e # set this to False if the backend does not support using time zones\n\u003e USE_TZ = False\n\u003e ```\n\nRun the migrations command to propagate changes you made to your models (creating a class, adding a field, deleting a model, etc.) into your database schema.\n\n```python\npython manage.py makemigrations customerapi\n\npython manage.py migrate customerapi\n```\n\nOnce migration is done successfully, you'll see that database objects are created in your database. You can connect to your database and verify. Quickstart available here: [Quickstart: Use Azure Data Studio to connect and query Azure SQL database](https://docs.microsoft.com/en-us/sql/azure-data-studio/quickstart-sql-database?view=sql-server-ver15)\n\n## Run sample locally\n\nExecute the below command, to start the development web server on the local machine. By default, the server runs on port 8000 on the IP address 127.0.0.1. You can pass in an IP address and port number explicitly.\n\nInitialize Django - this is needed only the first time\n\n```python\npython manage.py migrate\n\npython manage.py createsuperuser\n```\n\nand then run the server\n\n```python\npython manage.py runserver\n```\n\nOnce the Django application is running, you'll see something like:\n\n```bash\n...\nSystem check identified no issues (0 silenced).\nFebruary 04, 2022 - 14:32:15\nDjango version 4.0.2, using settings 'django-sql-project.settings'\nStarting development server at http://127.0.0.1:8000/\nQuit the server with CTRL-BREAK.\n```\n\nUsing a REST Client (such as [Visual Studio](https://learn.microsoft.com/aspnet/core/test/http-files), [Insomnia](https://insomnia.rest/), [Curl](https://curl.se/docs/httpscripting.html) or PowerShell's [Invoke-RestMethod](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/invoke-restmethod)), you can now call your API, for example:\n\n```bash\ncurl -X GET http://127.0.0.1:8000/customerapi/customer/\n```\n\nAnd you’ll get a response something like (based on available data in tables):\n\n```json\n[\n    {\"CustomerId\": 1, \"CustomerName\": \"Keith\"},{\"CustomerId\": 2, \"CustomerName\": \"Janet\"},{\"CustomerId\": 4, \"CustomerName\": \"Cortana\"},{\"CustomerId\": 5, \"CustomerName\": \"Michael\"},{\"CustomerId\": 7, \"CustomerName\": \"David\"},{\"CustomerId\": 8, \"CustomerName\": \"Mike\"}\n]\n```\n\nCheck out the [sample](https://github.com/azure-samples/azure-sql-db-django) to test all the CRUD operations.\n\n## Deploy your application code to Azure App Service\n\nAzure App service supports multiple methods to deploy your application code to Azure including support for GitHub Actions and all major CI/CD tools. This article focuses on how to deploy your code from your local workstation to Azure.\n\n### Prerequisites\n\nIf you don't have an Azure subscription, create a [free](https://azure.microsoft.com/en-us/free/) account before you begin.\n\nThis article requires that you're running the Azure CLI version 2.0 or later locally. To see the version installed, run the `az --version` command. If you need to install or upgrade, see [Install Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli).\n\nYou'll need to login to your account using the [az login](https://docs.microsoft.com/en-us/cli/azure/authenticate-azure-cli) command.\n\n```azurecli\naz login\n```\n\nIf you have multiple subscriptions, choose the appropriate subscription in which the resource should be created. Select the specific subscription ID under your account using [az account set](https://docs.microsoft.com/en-us/cli/azure/account?view=azure-cli-latest) command. Substitute the subscription ID property from the az login output for your subscription into the subscription ID placeholder.\n\n```azurecli\naz account set --subscription \u003csubscription id\u003e\n```\n\n\u003e Refer [this article](https://docs.microsoft.com/en-us/azure/app-service/configure-language-python), to know more about configuring a Linux Python app for Azure app Service.\n\n### Configure static files\n\n- In your settings file, define `STATIC_URL` and `STATIC_ROOT`, for example:\n\n```python\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/4.0/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = 'static'\n```\n\n- Run the `python manage.py collectstatic` to gather static files into a directory at `STATIC_ROOT` path for the admin site:\n\n```python\npython manage.py collectstatic\n```\n\n### Create the App Service webapp and deploy code from a local workspace\n\nIn the terminal, make sure you're in the repository root (`\u003cworking_folder\u003e\\azure-sql-db-django`) that contains the app code.\n\nRun the below [az webapp](https://docs.microsoft.com/en-us/cli/azure/webapp?view=azure-cli-latest) commands:\n\n\u003e [az webapp up](https://docs.microsoft.com/en-us/cli/azure/webapp?view=azure-cli-latest#az-webapp-up) create a webapp and deploy code from a local workspace to the app. Python apps are created as Linux apps by default.\n\n```azurecli\n# Create a web app and deploy the code\naz webapp up -g \u003cMyResourceGroup\u003e -l \u003clocation\u003e -p \u003cazure-sql-db-django-plan\u003e --sku B1 -n \u003cazure-sql-db-django-api\u003e -r 'PYTHON:3.9'\n\n# Configure database information as environment variables\naz webapp config appsettings set --settings DB_SERVER=\"\u003cazure-sql-server-name\u003e.database.windows.net\" DB_NAME=\"\u003cdb-name\u003e\" DB_USER=\"\u003cdb-user-id\u003e\" DB_PASSWORD=\"\u003cdb-password\u003e\"\n```\n\n- For the `--resource-group -g`, you can use the same resource group you created for the Database in the previous section.\n- For the `--location -l` argument, use the same location as you did for the database in the previous section.\n- Create the [App Service plan](https://docs.microsoft.com/en-us/azure/app-service/overview-hosting-plans) *azure-sql-db-django-plan* in the Basic pricing tier (B1), if it doesn't exist. --plan and --sku are optional.\n- For the `--runtime -r`, canonicalize runtime in the format of Framework|Version, e.g. \"PYTHON|3.9\". Allowed delimiters: \"|\" or \":\". Use `az webapp list-runtimes --linux --output table` for available list.\n- The app code expects to find database information in a number of environment variables. To set environment variables in App Service, you create \"app settings\" with the [az webapp config appsettings set](https://docs.microsoft.com/en-us/cli/azure/webapp/config/appsettings?view=azure-cli-latest#az_webapp_config_appsettings_set) command.\n\n\u003e [!NOTE]\n\u003e App Service detects a Django project by looking for a wsgi.py file in each subfolder, which `manage.py startproject` creates by default. When App Service finds that file, it loads the Django web app. For more information, see [Configure built-in Python image](https://docs.microsoft.com/en-us/azure/app-service/configure-language-python).\n\n## Browse to the app running on Azure App Service\n\nThe Python Django sample code is running a Linux container in App Service using a built-in image.\n\nBrowse to the deployed application in your web browser at the URL `https://\u003capp-name\u003e.azurewebsites.net/admin` or make a call to the API `https://\u003capp-name\u003e.azurewebsites.net/customerapi/customer/` using any other REST Client (such as [Visual Studio](https://learn.microsoft.com/aspnet/core/test/http-files), [Insomnia](https://insomnia.rest/), [Curl](https://curl.se/docs/httpscripting.html) or PowerShell's [Invoke-RestMethod](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/invoke-restmethod)), you can now call your API, for example:.\n\n**Congratulations!** You're running a Python Django app in Azure App Service for Linux, with Azure SQL database.\n\n\u003e [!TIP]\n\u003e You can use [mssql-django](https://github.com/microsoft/mssql-django) as a backend for your existing Django 4.0 project with no major change if that's already configured for MS SQL Server.\n\u0026nbsp;\n\nIf you encounter any issues or have any feedback about [mssql-django](https://github.com/microsoft/mssql-django), head over to our mssql-django project repository and submit an issue.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fazure-samples%2Fazure-sql-db-django","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fazure-samples%2Fazure-sql-db-django","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fazure-samples%2Fazure-sql-db-django/lists"}