You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#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.
13
14
---
14
15
15
16
# Quickstart: Use Azure Cache for Redis in Python
16
17
17
-
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 app to have access to a secure, dedicated cache that is accessible from any application within Azure.
18
19
19
20
## Skip to the code on GitHub
20
21
@@ -24,8 +25,8 @@ If you want to skip straight to the code, see the [Python quickstart](https://gi
24
25
25
26
- Azure subscription - [create one for free](https://azure.microsoft.com/free/)
26
27
- Python 3
27
-
- For macOS or Linux, download from [python.org](https://www.python.org/downloads/).
28
-
- For Windows 11, use the [Windows Store](https://apps.microsoft.com/search/publisher?name=Python+Software+Foundation&hl=en-us&gl=US).
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).
@@ -48,18 +49,23 @@ Fran, we probably need an include file on enabling EntraID
48
49
Blah blah blah, do the steps listed [here](cache-azure-active-directory-for-authentication)
49
50
-->
50
51
51
-
## Install the Microsoft Authentication Library
52
-
The [Microsoft Authentication Library (MSAL)](../../entra/identity-platform/msal-overview) allows you to acquire security tokens from Microsoft identity to authenticate users.
52
+
### Install the Microsoft Authentication Library
53
53
54
-
There's a [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`:
54
+
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.
55
55
56
-
```python
57
-
pip install azure-identity
58
-
```
56
+
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`:
57
+
58
+
```python
59
+
pip install azure-identity
60
+
```
61
+
62
+
### Create a sample python app
63
+
64
+
1. Create a new text file, add the following script, and save the file as `PythonApplication1.py`.
59
65
60
-
## Create a sample python app
66
+
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`.
61
67
62
-
Create a new text file, add the following script, and save the file as `PythonApplication1.py`. 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`. Replace `<Your Username>` with the values from your Microsoft EntraID user.
68
+
1. Replace `<Your Username>` with the values from your Microsoft EntraID user.
63
69
64
70
```python
65
71
import redis
@@ -104,80 +110,84 @@ Run `PythonApplication1.py` with Python. You should see results like the followi
104
110
105
111
## Create a sample python app with reauthentication
106
112
107
-
Microsoft EntraID access tokens have limited lifespans, [averaging 75 minutes](/azure/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.
108
-
109
-
Create a new text file, add the following script, and save the file as `PythonApplication2.py`. 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`. Replace `<Your Username>` with the values from your Microsoft EntraID user.
110
-
111
-
```python
112
-
import time
113
-
import logging
114
-
import redis
115
-
from azure.identity import DefaultAzureCredential
116
-
117
-
scope ="https://redis.azure.com/.default"
118
-
host ="<Your Host Name>"
119
-
port =6380
120
-
user_name ="<Your Username>"
121
-
122
-
defre_authentication():
123
-
_LOGGER= logging.getLogger(__name__)
124
-
cred = DefaultAzureCredential()
125
-
token = cred.get_token(scope)
126
-
r = redis.Redis(host=host,
127
-
port=port,
128
-
ssl=True, # ssl connection is required.
129
-
username=user_name,
130
-
password=token.token,
131
-
decode_responses=True)
132
-
max_retry =3
133
-
for index inrange(max_retry):
134
-
try:
135
-
if _need_refreshing(token):
136
-
_LOGGER.info("Refreshing token...")
137
-
tmp_token = cred.get_token(scope)
138
-
if tmp_token:
139
-
token = tmp_token
140
-
r.execute_command("AUTH", user_name, token.token)
141
-
result = r.ping()
142
-
print("Ping returned : "+str(result))
143
-
144
-
result = r.set("Message", "Hello!, The cache is working with Python!")
145
-
print("SET Message returned : "+str(result))
146
-
147
-
result = r.get("Message")
148
-
print("GET Message returned : "+ result)
149
-
150
-
result = r.client_list()
151
-
print("CLIENT LIST returned : ")
152
-
for c in result:
153
-
print(f"id : {c['id']}, addr : {c['addr']}")
154
-
break
155
-
except redis.ConnectionError:
156
-
_LOGGER.info("Connection lost. Reconnecting.")
157
-
token = cred.get_token(scope)
158
-
r = redis.Redis(host=host,
159
-
port=port,
160
-
ssl=True, # ssl connection is required.
161
-
username=user_name,
162
-
password=token.token,
163
-
decode_responses=True)
164
-
exceptException:
165
-
_LOGGER.info("Unknown failures.")
166
-
break
167
-
168
-
169
-
def_need_refreshing(token, refresh_offset=300):
170
-
returnnot token or token.expires_on - time.time() < refresh_offset
171
-
172
-
if__name__=='__main__':
173
-
re_authentication()
174
-
```
175
-
176
-
Run `PythonApplication2.py` with Python. You should see results like the following example:
177
-
178
-
:::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.":::
179
-
180
-
Unlike the first example, If your token expires, this example automatically refreshes it.
113
+
Microsoft EntraID 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.
114
+
115
+
1. Create a new text file, add the following script, and save the file as `PythonApplication2.py`.
116
+
117
+
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`.
118
+
119
+
1. Replace `<Your Username>` with the values from your Microsoft EntraID user.
120
+
121
+
```python
122
+
import time
123
+
import logging
124
+
import redis
125
+
from azure.identity import DefaultAzureCredential
126
+
127
+
scope ="https://redis.azure.com/.default"
128
+
host ="<Your Host Name>"
129
+
port =6380
130
+
user_name ="<Your Username>"
131
+
132
+
defre_authentication():
133
+
_LOGGER= logging.getLogger(__name__)
134
+
cred = DefaultAzureCredential()
135
+
token = cred.get_token(scope)
136
+
r = redis.Redis(host=host,
137
+
port=port,
138
+
ssl=True, # ssl connection is required.
139
+
username=user_name,
140
+
password=token.token,
141
+
decode_responses=True)
142
+
max_retry =3
143
+
for index inrange(max_retry):
144
+
try:
145
+
if _need_refreshing(token):
146
+
_LOGGER.info("Refreshing token...")
147
+
tmp_token = cred.get_token(scope)
148
+
if tmp_token:
149
+
token = tmp_token
150
+
r.execute_command("AUTH", user_name, token.token)
151
+
result = r.ping()
152
+
print("Ping returned : "+str(result))
153
+
154
+
result = r.set("Message", "Hello!, The cache is working with Python!")
155
+
print("SET Message returned : "+str(result))
156
+
157
+
result = r.get("Message")
158
+
print("GET Message returned : "+ result)
159
+
160
+
result = r.client_list()
161
+
print("CLIENT LIST returned : ")
162
+
for c in result:
163
+
print(f"id : {c['id']}, addr : {c['addr']}")
164
+
break
165
+
except redis.ConnectionError:
166
+
_LOGGER.info("Connection lost. Reconnecting.")
167
+
token = cred.get_token(scope)
168
+
r = redis.Redis(host=host,
169
+
port=port,
170
+
ssl=True, # ssl connection is required.
171
+
username=user_name,
172
+
password=token.token,
173
+
decode_responses=True)
174
+
exceptException:
175
+
_LOGGER.info("Unknown failures.")
176
+
break
177
+
178
+
179
+
def_need_refreshing(token, refresh_offset=300):
180
+
returnnot token or token.expires_on - time.time() < refresh_offset
181
+
182
+
if__name__=='__main__':
183
+
re_authentication()
184
+
```
185
+
186
+
1. Run `PythonApplication2.py`with Python. You should see results like the following example:
187
+
188
+
:::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.":::
189
+
190
+
Unlike the first example, If your token expires, this example automatically refreshes it.
181
191
182
192
## [Access Key Authentication](#tab/accesskey)
183
193
@@ -233,23 +243,8 @@ Run `PythonApplication1.py` with Python. You should see results like the followi
233
243
234
244
## Clean up resources
235
245
236
-
If you're finished with the Azure resource group and resources you created in this quickstart, you can delete them to avoid charges.
237
-
238
-
> [!IMPORTANT]
239
-
> 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.
240
-
241
-
To delete the resource group and its Redis Cache for Azure instance:
242
-
243
-
1. From the [Azure portal](https://portal.azure.com), search for and select **Resource groups**.
244
-
245
-
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.
246
-
247
-
1. On your resource group page, select **Delete resource group**.
248
-
249
-
1. Type the resource group name, and then select **Delete**.
250
-
251
-
:::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.":::
0 commit comments