Skip to content

Commit 765bb7d

Browse files
committed
Fixed links and linter issues
1 parent a599a4e commit 765bb7d

File tree

1 file changed

+97
-102
lines changed

1 file changed

+97
-102
lines changed

articles/azure-cache-for-redis/cache-python-get-started.md

Lines changed: 97 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@ ms.service: cache
1010
ms.devlang: python
1111
ms.custom: mvc, devx-track-python, mode-api, py-fresh-zinc
1212

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
---
1415

1516
# Quickstart: Use Azure Cache for Redis in Python
1617

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.
1819

1920
## Skip to the code on GitHub
2021

@@ -24,8 +25,8 @@ If you want to skip straight to the code, see the [Python quickstart](https://gi
2425

2526
- Azure subscription - [create one for free](https://azure.microsoft.com/free/)
2627
- 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).
2930

3031
## Create an Azure Cache for Redis instance
3132
[!INCLUDE [redis-cache-create](~/reusable-content/ce-skilling/azure/includes/azure-cache-for-redis/includes/redis-cache-create.md)]
@@ -48,18 +49,23 @@ Fran, we probably need an include file on enabling EntraID
4849
Blah blah blah, do the steps listed [here](cache-azure-active-directory-for-authentication)
4950
-->
5051

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
5353

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.
5555

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`.
5965

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`.
6167

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.
6369

6470
```python
6571
import redis
@@ -104,80 +110,84 @@ Run `PythonApplication1.py` with Python. You should see results like the followi
104110

105111
## Create a sample python app with reauthentication
106112

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-
def re_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 in range(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-
except Exception:
165-
_LOGGER.info("Unknown failures.")
166-
break
167-
168-
169-
def _need_refreshing(token, refresh_offset=300):
170-
return not 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+
def re_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 in range(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+
except Exception:
175+
_LOGGER.info("Unknown failures.")
176+
break
177+
178+
179+
def _need_refreshing(token, refresh_offset=300):
180+
return not 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.
181191

182192
## [Access Key Authentication](#tab/accesskey)
183193

@@ -233,23 +243,8 @@ Run `PythonApplication1.py` with Python. You should see results like the followi
233243

234244
## Clean up resources
235245

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.":::
246+
[!INCLUDE [cache-delete-resource-group](includes/cache-delete-resource-group.md)]
252247

253-
## Next steps
248+
## Related content
254249

255250
- [Create a simple ASP.NET web app that uses an Azure Cache for Redis.](./cache-web-app-howto.md)

0 commit comments

Comments
 (0)