Skip to content

Commit bf63470

Browse files
Standardize Python samples to use python-dotenv for environment variables
1 parent 90572bb commit bf63470

2 files changed

Lines changed: 26 additions & 14 deletions

File tree

azure-sql/database/azure-sql-passwordless-migration-python.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,13 @@ Create a user in Azure SQL Database. The user should correspond to the Azure acc
4848
Migrating to passwordless connections with [mssql-python](/sql/connect/python/mssql-python/python-sql-driver-mssql-python) requires only a connection string change. The driver has built-in support for Microsoft Entra authentication modes, eliminating the need for manual token handling.
4949

5050
```python
51-
import os
51+
from os import getenv
52+
from dotenv import load_dotenv
5253
from mssql_python import connect
5354

54-
connection_string = os.environ["AZURE_SQL_CONNECTIONSTRING"]
55+
load_dotenv()
56+
57+
connection_string = getenv("AZURE_SQL_CONNECTIONSTRING")
5558

5659
def get_all():
5760
with connect(connection_string) as conn:
@@ -61,10 +64,10 @@ def get_all():
6164
return
6265
```
6366

64-
To update the referenced connection string (`AZURE_SQL_CONNECTIONSTRING`) for local development, use the passwordless connection string format with `ActiveDirectoryDefault` authentication:
67+
To update the referenced connection string (`AZURE_SQL_CONNECTIONSTRING`) for local development, create a `.env` file in your project folder with the passwordless connection string format using `ActiveDirectoryDefault` authentication:
6568

6669
```text
67-
Server=tcp:<database-server-name>.database.windows.net,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryDefault
70+
AZURE_SQL_CONNECTIONSTRING=Server=tcp:<database-server-name>.database.windows.net,1433;Database=<database-name>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryDefault
6871
```
6972

7073
`ActiveDirectoryDefault` automatically discovers credentials from multiple sources (Azure CLI, environment variables, Visual Studio, etc.) without requiring interactive login. This is convenient for development but adds latency as it tries each credential source in sequence.

azure-sql/database/azure-sql-python-quickstart.md

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ For details and specific instructions for installing the `mssql-python` driver,
7878
fastapi
7979
uvicorn[standard]
8080
pydantic
81+
python-dotenv
8182
```
8283
8384
1. Install the requirements.
@@ -88,16 +89,20 @@ For details and specific instructions for installing the `mssql-python` driver,
8889
8990
## Configure the local connection string
9091
91-
For local development and connecting to Azure SQL Database, add the following `AZURE_SQL_CONNECTIONSTRING` environment variable. Replace the `<database-server-name>` and `<database-name>` placeholders with your own values. Example environment variables are shown for the Bash shell.
92+
For local development, create a `.env` file in your project folder to store your connection string. This keeps credentials out of your code and source control.
93+
94+
1. In the project folder, create a new file named `.env`.
95+
96+
1. Add the `AZURE_SQL_CONNECTIONSTRING` variable with your connection string. Replace the `<database-server-name>` and `<database-name>` placeholders with your own values.
9297
9398
The mssql-python driver has built-in support for Microsoft Entra authentication. Use the `Authentication` parameter to specify the authentication method.
9499
95100
## [DefaultAzureCredential](#tab/sql-default)
96101
97102
`ActiveDirectoryDefault` automatically discovers credentials from multiple sources (Azure CLI, environment variables, Visual Studio, etc.) without requiring interactive login. This is convenient for local development but is slower due to credential discovery.
98103
99-
```Bash
100-
export AZURE_SQL_CONNECTIONSTRING='Server=<database-server-name>.database.windows.net;Database=<database-name>;Authentication=ActiveDirectoryDefault;Encrypt=yes;TrustServerCertificate=no;'
104+
```text
105+
AZURE_SQL_CONNECTIONSTRING=Server=<database-server-name>.database.windows.net;Database=<database-name>;Authentication=ActiveDirectoryDefault;Encrypt=yes;TrustServerCertificate=no;
101106
```
102107

103108
> [!IMPORTANT]
@@ -110,20 +115,20 @@ export AZURE_SQL_CONNECTIONSTRING='Server=<database-server-name>.database.window
110115

111116
In Windows, Microsoft Entra Interactive Authentication can use Microsoft Entra multifactor authentication technology to set up connection. In this mode, an Azure Authentication dialog is triggered and allows the user to input credentials to complete the connection.
112117

113-
```Bash
114-
export AZURE_SQL_CONNECTIONSTRING='Server=<database-server-name>.database.windows.net;Database=<database-name>;Authentication=ActiveDirectoryInteractive;Encrypt=yes;TrustServerCertificate=no;'
118+
```text
119+
AZURE_SQL_CONNECTIONSTRING=Server=<database-server-name>.database.windows.net;Database=<database-name>;Authentication=ActiveDirectoryInteractive;Encrypt=yes;TrustServerCertificate=no;
115120
```
116121

117122
## [SQL Authentication](#tab/sql-auth)
118123

119124
You can directly authenticate to a SQL Server instance using a username and password.
120125

121-
```Bash
122-
export AZURE_SQL_CONNECTIONSTRING='Server=<database-server-name>.database.windows.net;Database=<database-name>;UID=<user-name>;PWD=<user-password>;Encrypt=yes;TrustServerCertificate=no;'
126+
```text
127+
AZURE_SQL_CONNECTIONSTRING=Server=<database-server-name>.database.windows.net;Database=<database-name>;UID=<user-name>;PWD=<user-password>;Encrypt=yes;TrustServerCertificate=no;
123128
```
124129

125130
> [!WARNING]
126-
> Use caution when managing connection strings that contain secrets such as usernames, passwords, or access keys. These secrets shouldn't be committed to source control or placed in unsecure locations where they might be accessed by unintended users.
131+
> Use caution when managing connection strings that contain secrets such as usernames, passwords, or access keys. These secrets shouldn't be committed to source control or placed in unsecure locations where they might be accessed by unintended users. Add `.env` to your `.gitignore` file to prevent accidentally committing secrets.
127132
128133
---
129134

@@ -137,24 +142,28 @@ You can get the details to create your connection string from the Azure portal:
137142

138143
In the project folder, create an *app.py* file and add the sample code. This code creates an API that:
139144

145+
- Loads configuration from a `.env` file using `python-dotenv`.
140146
- Retrieves an Azure SQL Database connection string from an environment variable.
141147
- Creates a `Persons` table in the database during startup (for testing scenarios only).
142148
- Defines a function to retrieve all `Person` records from the database.
143149
- Defines a function to retrieve one `Person` record from the database.
144150
- Defines a function to add new `Person` records to the database.
145151

146152
```python
147-
import os
153+
from os import getenv
148154
from typing import Union
155+
from dotenv import load_dotenv
149156
from fastapi import FastAPI
150157
from pydantic import BaseModel
151158
from mssql_python import connect
152159

160+
load_dotenv()
161+
153162
class Person(BaseModel):
154163
first_name: str
155164
last_name: Union[str, None] = None
156165

157-
connection_string = os.environ["AZURE_SQL_CONNECTIONSTRING"]
166+
connection_string = getenv("AZURE_SQL_CONNECTIONSTRING")
158167

159168
app = FastAPI()
160169

0 commit comments

Comments
 (0)