Skip to content

Commit 9145404

Browse files
committed
Merge branch 'patch-36' of https://github.com/v-rakegurram-MSFT/azure-docs-pr into fxl---update-python-sample
2 parents 1c3b490 + 9df0a8f commit 9145404

1 file changed

Lines changed: 35 additions & 152 deletions

File tree

articles/redis/python-get-started.md

Lines changed: 35 additions & 152 deletions
Original file line numberDiff line numberDiff line change
@@ -52,70 +52,23 @@ import redis
5252
from azure.identity import DefaultAzureCredential
5353
from redis_entraid.cred_provider import create_from_default_azure_credential
5454

55-
# Connection details for your cache
56-
# Get the connection details for the Redis instance
57-
redis_host = "contosob116.westus3.redis.azure.net"
58-
redis_port = 10000 #For an Azure
55+
redis_host = "<host-url>"
56+
redis_port = 10000 # Managed Redis default port
5957

60-
print("🚀 Starting Azure Redis Cache connection test...")
61-
print(f"📡 Connecting to: {redis_host}:{redis_port}")
58+
credential_provider = create_from_default_azure_credential(
59+
("https://redis.azure.com/.default",),
60+
)
6261

63-
# Validate configuration
64-
if not redis_host or not redis_port:
65-
print("❌ Error: Redis host and port must be configured")
66-
exit(1)
62+
r = redis.Redis(
63+
host=redis_host,
64+
port=redis_port,
65+
ssl=True,
66+
decode_responses=True,
67+
credential_provider=credential_provider
68+
)
6769

68-
print() # Add a new line
69-
70-
try:
71-
# Create credential provider using DefaultAzureCredential for Azure Entra ID authentication
72-
credential_provider = create_from_default_azure_credential(
73-
("https://redis.azure.com/.default",),)
74-
75-
# Create a Redis client with Azure Entra ID authentication
76-
r = redis.Redis(host=redis_host,
77-
port=redis_port,
78-
ssl=True,
79-
decode_responses=True,
80-
credential_provider=credential_provider,
81-
socket_timeout=10,
82-
socket_connect_timeout=10
83-
)
84-
```
85-
86-
## Code to test a connection
87-
88-
In the next section, test the connection using the Redis command `ping` that returns the `True` value.
89-
90-
```python
91-
# Ping the Redis server to test the connection
92-
result = r.ping()
93-
if result:
94-
print("Ping returned: ", result)
9570
```
9671

97-
## Code set a key, get a key
98-
99-
In this section, use a basic `set` and `get` sequence to start using the Redis cache in the simplest way to get started.
100-
101-
```python
102-
# Create a simple set and get operation
103-
result = r.set("Message", "Hello, The cache is working with Python!")
104-
print("✅ SET Message succeeded: " + str(result))
105-
print() # Add a new line
106-
107-
value = r.get("Message")
108-
109-
if value is not None:
110-
print("✅ GET Message returned : " + str(value))
111-
print() # Add a new line
112-
else:
113-
print("⚠️ GET Message returned None")
114-
print() # Add a new line
115-
116-
print("🎉 All Redis operations completed successfully!")
117-
print() # Add a new line
118-
```
11972

12073
Before you can run this code, you must add yourself as a Redis user to the cache.
12174

@@ -126,115 +79,45 @@ You should also [add users or a System principal to your cache](entra-for-authen
12679
The result looks like this:
12780

12881
```console
129-
C:\utils\python-quickstart>python quickstart-amr.py
130-
🚀 Starting Azure Redis Cache connection test...
131-
📡 Connecting to: contosob116.westus3.redis.azure.net:10000
132-
133-
✅ Ping returned : True
134-
135-
✅ SET Message succeeded: True
136-
137-
✅ GET Message returned : Hello, The cache is working with Python!
138-
139-
🎉 All Redis operations completed successfully!
140-
141-
🔐 Redis connection closed
82+
PING: True
83+
GET: Hello from Azure Managed Redis!
14284

14385
```
14486

14587
Here, you can see this code sample in its entirety. The code contains some error checking omitted from the earlier code explanations for simplicity. The final step is closing the connection to the cache.
14688

14789
```python
148-
# Python Quickstart using Azure Entra ID authentication
149-
# Azure Managed Redis cache that you created using the Azure portal, or CLI
150-
# This script demonstrates secure connection using Microsoft Entra ID authentication
151-
# This script demonstrates secure connection using the default Azure credential provider
152-
# You should be a user on the cache and logged in to Azure CLI with the same account using `az login`
153-
15490
import redis
15591
from azure.identity import DefaultAzureCredential
15692
from redis_entraid.cred_provider import create_from_default_azure_credential
15793

158-
# Connection details for your cache
159-
# Get the connection details for the Redis instance
160-
redis_host = "<host-url>" # Replace with your cache info
161-
redis_port = <port number> # Replace with your cache info
162-
163-
print("🚀 Starting Azure Redis Cache connection test...")
164-
print(f"📡 Connecting to: {redis_host}:{redis_port}")
94+
redis_host = "<host-url>"
95+
redis_port = 10000 # Managed Redis default port
16596

166-
# Validate configuration
167-
if not redis_host or not redis_port:
168-
print("❌ Error: Redis host and port must be configured")
169-
exit(1)
170-
171-
print() # Add a new line
97+
credential_provider = create_from_default_azure_credential(
98+
("https://redis.azure.com/.default",),
99+
)
172100

173101
try:
174-
# Create credential provider using DefaultAzureCredential for Azure Entra ID authentication
175-
credential_provider = create_from_default_azure_credential(
176-
("https://redis.azure.com/.default",),)
177-
178-
# Create a Redis client with Azure Entra ID authentication
179-
r = redis.Redis(host=redis_host,
180-
port=redis_port,
181-
ssl=True,
182-
decode_responses=True,
183-
credential_provider=credential_provider,
184-
socket_timeout=10,
185-
socket_connect_timeout=10
186-
)
187-
188-
# Test connection
189-
result = r.ping()
190-
print("✅ Ping returned : " + str(result))
191-
print() # Add a new line
192-
193-
# Create a simple set and get operation
194-
result = r.set("Message", "Hello, The cache is working with Python!")
195-
print("✅ SET Message succeeded: " + str(result))
196-
print() # Add a new line
197-
198-
value = r.get("Message")
199-
200-
if value is not None:
201-
print("✅ GET Message returned : " + str(value))
202-
print() # Add a new line
203-
else:
204-
print("⚠️ GET Message returned None")
205-
print() # Add a new line
206-
207-
print("🎉 All Redis operations completed successfully!")
208-
print() # Add a new line
209-
210-
except redis.ConnectionError as e:
211-
print(f"❌ Connection error: {e}")
212-
print("💡 Check if Redis host and port are correct, and ensure network connectivity")
213-
print() # Add a new line
214-
except redis.AuthenticationError as e:
215-
print(f"❌ Authentication error: {e}")
216-
print("💡 Check if Azure Entra ID authentication is properly configured")
217-
print() # Add a new line
218-
except redis.TimeoutError as e:
219-
print(f"❌ Timeout error: {e}")
220-
print("💡 Check network latency and Redis server performance")
221-
print() # Add a new line
102+
r = redis.Redis(
103+
host=redis_host,
104+
port=redis_port,
105+
ssl=True,
106+
decode_responses=True,
107+
credential_provider=credential_provider,
108+
socket_timeout=10,
109+
socket_connect_timeout=10
110+
)
111+
112+
print("PING:", r.ping())
113+
r.set("Message", "Hello from Azure Managed Redis!")
114+
print("GET:", r.get("Message"))
115+
222116
except Exception as e:
223-
print(f"❌ Unexpected error: {e}")
224-
if "999" in str(e):
225-
print("💡 Error 999 typically indicates a network connectivity issue or firewall restriction")
226-
print(" - Verify the Redis hostname is correct")
227-
print(" - Verify that you have logged in with Az CLI")
228-
print(" - Ensure the Redis cache is running and accessible")
229-
print() # Add a new line
117+
print(f"Error: {e}")
230118
finally:
231-
# Clean up connection if it exists
232119
if 'r' in locals():
233-
try:
234-
r.close()
235-
print("🔐 Redis connection closed")
236-
except Exception as e:
237-
print(f"❌ Error closing connection: {e}")
120+
r.close()
238121

239122
```
240123

0 commit comments

Comments
 (0)