Skip to content

Commit 3540cfe

Browse files
committed
Converted to connection URI and environment variables
1 parent d87229f commit 3540cfe

File tree

1 file changed

+92
-45
lines changed

1 file changed

+92
-45
lines changed

articles/postgresql/flexible-server/connect-python.md

Lines changed: 92 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -92,31 +92,34 @@ In this section, you add authentication code to your working directory and perfo
9292

9393
#### [Passwordless (Recommended)](#tab/passwordless)
9494

95-
1. Copy the following code into an editor and save it in a file named *get_conn_str.py*.
95+
1. Copy the following code into an editor and save it in a file named *get_conn.py*.
9696

9797
```python
98+
import urllib.parse
99+
import os
100+
98101
from azure.identity import DefaultAzureCredential
99102

100103
# IMPORTANT! This code is for demonstration purposes only. It's not suitable for use in production.
101104
# For example, tokens issued by Microsoft Entra ID have a limited lifetime (24 hours by default).
102105
# In production code, you need to implement a token refresh policy.
103106

104-
def get_connection_string():
107+
def get_connection_uri():
105108

106-
# Update connection string information
107-
host = "<server-name>"
108-
dbname = "<database-name>"
109-
user = "<username>"
110-
sslmode = "require"
111-
109+
# Read URI parameters from the environment
110+
dbhost = os.environ['DBHOST']
111+
dbname = os.environ['DBNAME']
112+
dbuser = urllib.parse.quote(os.environ['DBUSER'])
113+
sslmode = os.environ['SSLMODE']
114+
112115
# Use passwordless authentication via DefaultAzureCredential.
113-
# Call get_token() to get a token from Microsft Entra ID and add it as the password in the connection string.
116+
# Call get_token() to get a token from Microsft Entra ID and add it as the password in the URI.
114117
# Note the requested scope parameter in the call to get_token, "https://ossrdbms-aad.database.windows.net/.default".
115118
credential = DefaultAzureCredential()
116-
token=credential.get_token("https://ossrdbms-aad.database.windows.net/.default").token
119+
password=credential.get_token("https://ossrdbms-aad.database.windows.net/.default").token
117120

118-
conn_string = f"host={host} user={user} dbname={dbname} password={token} sslmode={sslmode}"
119-
return conn_string
121+
db_uri = f"postgresql://{dbuser}:{password}@{dbhost}/{dbname}?sslmode={sslmode}"
122+
return db_uri
120123
```
121124

122125
1. Get database connection information.
@@ -125,11 +128,33 @@ In this section, you add authentication code to your working directory and perfo
125128
1. On the server's **Overview** page, copy the fully qualified **Server name**. The fully qualified **Server name** is always of the form *\<my-server-name>.postgres.database.azure.com*.
126129
1. On the left menu, under **Security**, select **Authentication**. Make sure your account is listed under **Microsoft Entra Admins**. If it isn't, complete the steps in [Configure Microsoft Entra integration on the server (passwordless only)](#configure-microsoft-entra-integration-on-the-server-passwordless-only).
127130

128-
1. Replace the following placeholder values in the code:
131+
1. Set enviornment variables for the connection URI elements:
132+
133+
### [Windows](#tab/cmd)
134+
135+
```cmd
136+
set DBHOST=<server-name>
137+
set DBNAME=<database-name>
138+
set DBUSER=<username>
139+
set SSLMODE=require
140+
```
141+
142+
### [macOS/Linux](#tab/bash)
129143

130-
- `<server-name>` with the value you copied from the Azure portal.
131-
- `<username>` with your Azure user name; for example. `john@contoso.com`.
132-
- `<database-name>` with the name of your Azure Database for PostgreSQL flexible server database. A default database named *postgres* was automatically created when you created your server. You can rename that database or create a new database by using SQL commands.
144+
```bash
145+
DBHOST=<server-name>
146+
DBNAME=<database-name>
147+
DBUSER=<username>
148+
SSLMODE=require
149+
```
150+
151+
---
152+
153+
Replace the following placeholder values in the commands:
154+
155+
* `<server-name>` with the value you copied from the Azure portal.
156+
* `<username>` with your Azure user name; for example. `john@contoso.com`.
157+
* `<database-name>` with the name of your Azure Database for PostgreSQL flexible server database. A default database named *postgres* was automatically created when you created your server. You can use that database or create a new database by using SQL commands.
133158

134159
1. Sign in to Azure on your workstation. You can sign in using the Azure CLI, Azure PowerShell, or Azure Developer CLI. For example, to sign in via the Azure CLI, enter this command:
135160

@@ -141,26 +166,24 @@ In this section, you add authentication code to your working directory and perfo
141166

142167
#### [Password](#tab/password)
143168

144-
1. Copy the following code into an editor and save it in a file named *get_conn_str.py*.
169+
1. Copy the following code into an editor and save it in a file named *get_conn.py*.
145170

146171
```python
172+
import urllib.parse
173+
import os
147174

148-
# IMPORTANT! This code is for demonstration purposes only. It's not suitable for use in production.
149-
# For example, in production you should never place a password directly in code. Instead, you should use some
150-
# other mechanism, like environment variables or Azure keyvault to hold passwords.
151-
152-
def get_connection_string():
175+
def get_connection_uri():
153176

154-
# Update connection string information
155-
host = "<server-name>"
156-
dbname = "<database-name>"
157-
user = "<username>"
158-
password = "<password>"
159-
sslmode = "require"
160-
161-
# Construct connection string
162-
conn_string = f"host={host} user={user} dbname={dbname} password={password} sslmode={sslmode}"
163-
return conn_string
177+
# Read URI parameters from the environment
178+
dbhost = os.environ['DBHOST']
179+
dbname = os.environ['DBNAME']
180+
dbuser = urllib.parse.quote(os.environ['DBUSER'])
181+
password = os.environ['DBPASSWORD']
182+
sslmode = os.environ['SSLMODE']
183+
184+
# Construct connection URI
185+
db_uri = f"postgresql://{dbuser}:{password}@{dbhost}/{dbname}?sslmode={sslmode}"
186+
return db_uri
164187
```
165188

166189
1. Get database connection information.
@@ -172,11 +195,35 @@ In this section, you add authentication code to your working directory and perfo
172195

173196
<!--![Azure Database for PostgreSQL server name](./media/connect-python/1-connection-string.png)-->
174197

175-
1. Replace the following placeholder values in the code:
198+
1. Set enviornment variables for the connection URI elements:
199+
200+
### [Windows](#tab/cmd)
201+
202+
```cmd
203+
set DBHOST=<server-name>
204+
set DBNAME=<database-name>
205+
set DBUSER=<username>
206+
set DBPASSWORD=<password>
207+
set SSLMODE=require
208+
```
209+
210+
### [macOS/Linux](#tab/bash)
211+
212+
```bash
213+
DBHOST=<server-name>
214+
DBNAME=<database-name>
215+
DBUSER=<username>
216+
DBPASSWORD=<password>
217+
SSLMODE=require
218+
```
219+
220+
---
221+
222+
Replace the following placeholder values in the commands:
176223

177-
- `<server-name>` and `<username>` with the values you copied from the Azure portal.
178-
- `<password>` with your server password.
179-
- `<database-name>` with the name of your Azure Database for PostgreSQL flexible server database. A default database named *postgres* was automatically created when you created your server. You can rename that database or create a new database by using SQL commands.
224+
* `<server-name>` and `<username>` with the values you copied from the Azure portal.
225+
* `<password>` with your server password.
226+
* `<database-name>` with the name of your Azure Database for PostgreSQL flexible server database. A default database named *postgres* was automatically created when you created your server. You can rename that database or create a new database by using SQL commands.
180227

181228
---
182229

@@ -198,9 +245,9 @@ The following code example connects to your Azure Database for PostgreSQL flexib
198245

199246
```Python
200247
import psycopg2
201-
from get_conn_str import get_connection_string
248+
from get_conn import get_connection_uri
202249

203-
conn_string = get_connection_string()
250+
conn_string = get_connection_uri()
204251

205252
conn = psycopg2.connect(conn_string)
206253
print("Connection established")
@@ -241,9 +288,9 @@ The following code example connects to your Azure Database for PostgreSQL flexib
241288

242289
```Python
243290
import psycopg2
244-
from get_conn_str import get_connection_string
291+
from get_conn import get_connection_uri
245292

246-
conn_string = get_connection_string()
293+
conn_string = get_connection_uri()
247294

248295
conn = psycopg2.connect(conn_string)
249296
print("Connection established")
@@ -278,9 +325,9 @@ The following code example connects to your Azure Database for PostgreSQL flexib
278325

279326
```Python
280327
import psycopg2
281-
from get_conn_str import get_connection_string
328+
from get_conn import get_connection_uri
282329

283-
conn_string = get_connection_string()
330+
conn_string = get_connection_uri()
284331

285332
conn = psycopg2.connect(conn_string)
286333
print("Connection established")
@@ -298,13 +345,13 @@ conn.close()
298345

299346
## Delete data
300347

301-
The following code example connects to your Azure Database for PostgreSQL flexible server database and uses cursor.execute with the SQL **DELETE** statement to delete an inventory item that you previously inserted.
348+
The following code example connects to your Azure Database for PostgreSQL flexible server database and uses cursor.execute with the SQL **DELETE** statement to delete an inventory item that you previously inserted.
302349

303350
```Python
304351
import psycopg2
305-
from get_conn_str import get_connection_string
352+
from get_conn import get_connection_uri
306353

307-
conn_string = get_connection_string()
354+
conn_string = get_connection_uri()
308355

309356
conn = psycopg2.connect(conn_string)
310357
print("Connection established")

0 commit comments

Comments
 (0)