Skip to content

Commit 0df5a09

Browse files
Merge pull request #280070 from flang-msft/fxl-msfteegarden-patch-67-python-quickstart-278246
Fxl msfteegarden patch 67 python quickstart 278246
2 parents 1e86212 + 11c0936 commit 0df5a09

File tree

4 files changed

+209
-45
lines changed

4 files changed

+209
-45
lines changed
Lines changed: 178 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
11
---
22
title: 'Quickstart: Use Azure Cache for Redis in Python'
3-
description: In this quickstart, you learn how to create a Python App that uses Azure Cache for Redis.
3+
description: In this quickstart, you learn how to create a Python script that uses Azure Cache for Redis.
44
author: flang-msft
55

66
ms.author: franlanglois
7-
8-
ms.date: 02/15/2023
7+
ms.date: 07/09/2024
98
ms.topic: quickstart
109
ms.service: cache
1110
ms.devlang: python
1211
ms.custom: mvc, devx-track-python, mode-api, py-fresh-zinc
12+
13+
#customer intent: As a cloud developer, I want to quickly see a cache so that understand how to use Python with Azure Cache for Redis.
1314
---
15+
1416
# Quickstart: Use Azure Cache for Redis in Python
1517

16-
In this article, you incorporate Azure Cache for Redis into a Python app to have access to a secure, dedicated cache that is accessible from any application within Azure.
18+
In this Quickstart, you incorporate Azure Cache for Redis into a Python script to have access to a secure, dedicated cache that is accessible from any application within Azure.
1719

1820
## Skip to the code on GitHub
1921

@@ -23,40 +25,191 @@ If you want to skip straight to the code, see the [Python quickstart](https://gi
2325

2426
- Azure subscription - [create one for free](https://azure.microsoft.com/free/)
2527
- Python 3
26-
- For macOS or Linux, download from [python.org](https://www.python.org/downloads/).
27-
- For Windows 11, use the [Windows Store](https://www.microsoft.com/en-us/p/python-3/9nblggh083nz?activetab=pivot:overviewtab).
28+
- For macOS or Linux, download from [python.org](https://www.python.org/downloads/).
29+
- For Windows 11, use the [Windows Store](https://apps.microsoft.com/search/publisher?name=Python+Software+Foundation&hl=en-us&gl=US).
2830

2931
## Create an Azure Cache for Redis instance
3032
[!INCLUDE [redis-cache-create](~/reusable-content/ce-skilling/azure/includes/azure-cache-for-redis/includes/redis-cache-create.md)]
3133

32-
[!INCLUDE [redis-cache-create](includes/redis-cache-access-keys.md)]
34+
## Install redis-py library
3335

34-
## Install redis-py
35-
36-
[Redis-py](https://pypi.org/project/redis/) is a Python interface to Azure Cache for Redis. Use the Python packages tool, `pip`, to install the `redis-py` package from a command prompt.
36+
[Redis-py](https://pypi.org/project/redis/) is a Python interface to Azure Cache for Redis. Use the Python packages tool, `pip`, to install the `redis-py` package from a command prompt.
3737

3838
The following example used `pip3` for Python 3 to install `redis-py` on Windows 11 from an Administrator command prompt.
3939

4040
:::image type="content" source="media/cache-python-get-started/cache-python-install-redis-py.png" alt-text="Screenshot of a terminal showing an install of redis-py interface to Azure Cache for Redis.":::
4141

42-
## Read and write to the cache
43-
44-
Run Python from the command line and test your cache by using the following code. Replace `<Your Host Name>` and `<Your Access Key>` with the values from your Azure Cache for Redis instance. Your host name is of the form `<DNS name>.redis.cache.windows.net`.
42+
## Create a Python script to access your cache
43+
44+
Create a Python script to that uses either Microsoft Entra ID or access keys to connect to an Azure Cache for Redis. We recommend you use Microsoft Entra ID.
45+
46+
## [Microsoft Entra ID Authentication (recommended)](#tab/entraid)
47+
48+
[!INCLUDE [cache-entra-access](includes/cache-entra-access.md)]
49+
50+
### Install the Microsoft Authentication Library
51+
52+
1. Install the [Microsoft Authentication Library (MSAL)](/entra/identity-platform/msal-overview). This library allows you to acquire security tokens from Microsoft identity to authenticate users.
53+
54+
1. You can use the [Python Azure identity client library](/python/api/overview/azure/identity-readme) available that uses MSAL to provide token authentication support. Install this library using `pip`:
55+
56+
```python
57+
pip install azure-identity
58+
```
59+
60+
### Create a Python script using Microsoft Entra ID
61+
62+
1. Create a new text file, add the following script, and save the file as `PythonApplication1.py`.
63+
64+
1. Replace `<Your Host Name>` with the value from your Azure Cache for Redis instance. Your host name is of the form `<DNS name>.redis.cache.windows.net`.
65+
66+
1. Replace `<Your Username>` with the values from your Microsoft Entra ID user.
67+
68+
```python
69+
import redis
70+
from azure.identity import DefaultAzureCredential
71+
72+
scope = "https://redis.azure.com/.default"
73+
host = "<Your Host Name>"
74+
port = 6380
75+
user_name = "<Your Username>"
76+
77+
78+
def hello_world():
79+
cred = DefaultAzureCredential()
80+
token = cred.get_token(scope)
81+
r = redis.Redis(host=host,
82+
port=port,
83+
ssl=True, # ssl connection is required.
84+
username=user_name,
85+
password=token.token,
86+
decode_responses=True)
87+
result = r.ping()
88+
print("Ping returned : " + str(result))
89+
90+
result = r.set("Message", "Hello!, The cache is working with Python!")
91+
print("SET Message returned : " + str(result))
92+
93+
result = r.get("Message")
94+
print("GET Message returned : " + result)
95+
96+
result = r.client_list()
97+
print("CLIENT LIST returned : ")
98+
for c in result:
99+
print(f"id : {c['id']}, addr : {c['addr']}")
100+
101+
if __name__ == '__main__':
102+
hello_world()
103+
```
104+
105+
1. Before you run your Python code from a Terminal, make sure you authorize the terminal for using Microsoft Entra ID.
106+
107+
`azd auth login`
108+
109+
1. Run `PythonApplication1.py` with Python. You should see results like the following example:
110+
111+
:::image type="content" source="media/cache-python-get-started/cache-python-completed.png" alt-text="Screenshot of a terminal showing a Python script to test cache access.":::
112+
113+
### Create a Python script using reauthentication
114+
115+
Microsoft Entra ID access tokens have limited lifespans, [averaging 75 minutes](/entra/identity-platform/configurable-token-lifetimes#token-lifetime-policies-for-access-saml-and-id-tokens). In order to maintain a connection to your cache, you need to refresh the token. This example demonstrates how to do this using Python.
116+
117+
1. Create a new text file, add the following script. Then, save the file as `PythonApplication2.py`.
118+
119+
1. Replace `<Your Host Name>` with the value from your Azure Cache for Redis instance. Your host name is of the form `<DNS name>.redis.cache.windows.net`.
120+
121+
1. Replace `<Your Username>` with the values from your Microsoft Entra ID user.
122+
123+
```python
124+
import time
125+
import logging
126+
import redis
127+
from azure.identity import DefaultAzureCredential
128+
129+
scope = "https://redis.azure.com/.default"
130+
host = "<Your Host Name>"
131+
port = 6380
132+
user_name = "<Your Username>"
133+
134+
def re_authentication():
135+
_LOGGER = logging.getLogger(__name__)
136+
cred = DefaultAzureCredential()
137+
token = cred.get_token(scope)
138+
r = redis.Redis(host=host,
139+
port=port,
140+
ssl=True, # ssl connection is required.
141+
username=user_name,
142+
password=token.token,
143+
decode_responses=True)
144+
max_retry = 3
145+
for index in range(max_retry):
146+
try:
147+
if _need_refreshing(token):
148+
_LOGGER.info("Refreshing token...")
149+
tmp_token = cred.get_token(scope)
150+
if tmp_token:
151+
token = tmp_token
152+
r.execute_command("AUTH", user_name, token.token)
153+
result = r.ping()
154+
print("Ping returned : " + str(result))
155+
156+
result = r.set("Message", "Hello!, The cache is working with Python!")
157+
print("SET Message returned : " + str(result))
158+
159+
result = r.get("Message")
160+
print("GET Message returned : " + result)
161+
162+
result = r.client_list()
163+
print("CLIENT LIST returned : ")
164+
for c in result:
165+
print(f"id : {c['id']}, addr : {c['addr']}")
166+
break
167+
except redis.ConnectionError:
168+
_LOGGER.info("Connection lost. Reconnecting.")
169+
token = cred.get_token(scope)
170+
r = redis.Redis(host=host,
171+
port=port,
172+
ssl=True, # ssl connection is required.
173+
username=user_name,
174+
password=token.token,
175+
decode_responses=True)
176+
except Exception:
177+
_LOGGER.info("Unknown failures.")
178+
break
179+
180+
181+
def _need_refreshing(token, refresh_offset=300):
182+
return not token or token.expires_on - time.time() < refresh_offset
183+
184+
if __name__ == '__main__':
185+
re_authentication()
186+
```
187+
188+
1. Run `PythonApplication2.py` with Python. You should see results like the following example:
189+
190+
:::image type="content" source="media/cache-python-get-started/cache-python-completed.png" alt-text="Screenshot of a terminal showing a Python script to test cache access.":::
191+
192+
Unlike the first example, If your token expires, this example automatically refreshes it.
193+
194+
## [Access Key Authentication](#tab/accesskey)
195+
196+
[!INCLUDE [redis-cache-access-keys](includes/redis-cache-access-keys.md)]
197+
198+
### Read and write to the cache from the command line
199+
200+
Run [Python from the command line](https://docs.python.org/3/faq/windows.html#id2) to test your cache. First, initiate the Python interpreter in your command line by typing `py`, and then use the following code. Replace `<Your Host Name>` and `<Your Access Key>` with the values from your Azure Cache for Redis instance. Your host name is of the form `<DNS name>.redis.cache.windows.net`.
45201

46202
```python
47203
>>> import redis
48-
>>> r = redis.StrictRedis(host='<Your Host Name>',
204+
>>> r = redis.Redis(host='<Your Host Name>',
49205
port=6380, db=0, password='<Your Access Key>', ssl=True)
50206
>>> r.set('foo', 'bar')
51207
True
52208
>>> r.get('foo')
53209
b'bar'
54210
```
55211

56-
> [!IMPORTANT]
57-
> For Azure Cache for Redis version 3.0 or higher, TLS/SSL certificate check is enforced. `ssl_ca_certs` must be explicitly set when connecting to Azure Cache for Redis. For RedHat Linux, `ssl_ca_certs` are in the `/etc/pki/tls/certs/ca-bundle.crt` certificate module.
58-
59-
## Create a Python sample app
212+
### Create a Python script using access keys
60213

61214
Create a new text file, add the following script, and save the file as `PythonApplication1.py`. Replace `<Your Host Name>` and `<Your Access Key>` with the values from your Azure Cache for Redis instance. Your host name is of the form `<DNS name>.redis.cache.windows.net`.
62215

@@ -66,7 +219,7 @@ import redis
66219
myHostname = "<Your Host Name>"
67220
myPassword = "<Your Access Key>"
68221

69-
r = redis.StrictRedis(host=myHostname, port=6380,
222+
r = redis.Redis(host=myHostname, port=6380,
70223
password=myPassword, ssl=True)
71224

72225
result = r.ping()
@@ -76,7 +229,7 @@ result = r.set("Message", "Hello!, The cache is working with Python!")
76229
print("SET Message returned : " + str(result))
77230

78231
result = r.get("Message")
79-
print("GET Message returned : " + result.decode("utf-8"))
232+
print("GET Message returned : " + result)
80233

81234
result = r.client_list()
82235
print("CLIENT LIST returned : ")
@@ -88,25 +241,12 @@ Run `PythonApplication1.py` with Python. You should see results like the followi
88241

89242
:::image type="content" source="media/cache-python-get-started/cache-python-completed.png" alt-text="Screenshot of a terminal showing a Python script to test cache access.":::
90243

91-
## Clean up resources
92-
93-
If you're finished with the Azure resource group and resources you created in this quickstart, you can delete them to avoid charges.
94-
95-
> [!IMPORTANT]
96-
> Deleting a resource group is irreversible, and the resource group and all the resources in it are permanently deleted. If you created your Azure Cache for Redis instance in an existing resource group that you want to keep, you can delete just the cache by selecting **Delete** from the cache **Overview** page.
97-
98-
To delete the resource group and its Redis Cache for Azure instance:
99-
100-
1. From the [Azure portal](https://portal.azure.com), search for and select **Resource groups**.
101-
102-
1. In the **Filter by name** text box, enter the name of the resource group that contains your cache instance, and then select it from the search results.
244+
---
103245

104-
1. On your resource group page, select **Delete resource group**.
246+
<!-- Clean up resources -->
105247

106-
1. Type the resource group name, and then select **Delete**.
107-
108-
:::image type="content" source="./media/cache-python-get-started/delete-your-resource-group-for-azure-cache-for-redis.png" alt-text="Screenshot of the Azure portal showing how to delete the resource group for Azure Cache for Redis.":::
248+
[!INCLUDE [cache-delete-resource-group](includes/cache-delete-resource-group.md)]
109249

110-
## Next steps
250+
## Related content
111251

112-
- [Create a simple ASP.NET web app that uses an Azure Cache for Redis.](./cache-web-app-howto.md)
252+
- [Create a ASP.NET web app that uses an Azure Cache for Redis.](./cache-web-app-howto.md)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
ms.service: cache
3+
ms.topic: include
4+
ms.date: 07/08/2024
5+
ms.author: franlanglois
6+
author: flang-msft
7+
---
8+
9+
### Enable Microsoft Entra ID authentication on your cache
10+
11+
If you have a cache already, you first want to check to see if Microsoft Entra Authentication has been enabled. If not, then enable it. We recommend using Microsoft Entra ID for your applications.
12+
13+
1. In the Azure portal, select the Azure Cache for Redis instance where you'd like to use Microsoft Entra token-based authentication.
14+
15+
1. Select **Authentication** from the Resource menu.
16+
17+
1. Check in the working pane to see if **Enable Microsoft Entra Authentication** is checked. If so, you can move on.
18+
19+
1. Select **Enable Microsoft Entra Authentication**, and enter the name of a valid user. The user you enter is automatically assigned _Data Owner Access Policy_ by default when you select **Save**. You can also enter a managed identity or service principal to connect to your cache instance.
20+
21+
:::image type="content" source="media/cache-entra-access/cache-enable-microsoft-entra.png" alt-text="Screenshot showing authentication selected in the resource menu and the enable Microsoft Entra authentication checked.":::
22+
23+
1. A popup dialog box displays asking if you want to update your configuration, and informing you that it takes several minutes. Select **Yes.**
24+
25+
> [!IMPORTANT]
26+
> Once the enable operation is complete, the nodes in your cache instance reboots to load the new configuration. We recommend performing this operation during your maintenance window or outside your peak business hours. The operation can take up to 30 minutes.
27+
28+
For information on using Microsoft Entra ID with Azure CLI, see the [references pages for identity](/cli/azure/redis/identity).
172 KB
Loading

articles/azure-cache-for-redis/includes/redis-cache-access-keys.md

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
11
---
2-
title: "include file"
3-
description: "include file"
4-
services: cache
5-
author: flang-msft
62
ms.service: cache
7-
ms.topic: "include"
8-
ms.date: 04/25/2024
3+
ms.topic: include
4+
ms.date: 07/03/2024
95
ms.author: franlanglois
10-
ms.custom: "include file"
6+
author: flang-msft
117
---
128

139
### Retrieve host name, ports, and access keys from the Azure portal

0 commit comments

Comments
 (0)