Skip to content

Commit b40cf60

Browse files
authored
Update cache-python-get-started.md
1 parent c6d50c8 commit b40cf60

File tree

1 file changed

+80
-7
lines changed

1 file changed

+80
-7
lines changed

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

Lines changed: 80 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,9 @@ import redis
5858
from azure.identity import DefaultAzureCredential
5959

6060
scope = "https://redis.azure.com/.default"
61-
host = "<Your Host Name>" # Required
62-
port = 6380 # Required
63-
user_name = "<Your Username>" # Required
61+
host = "<Your Host Name>"
62+
port = 6380
63+
user_name = "<Your Username>"
6464

6565

6666
def hello_world():
@@ -94,6 +94,82 @@ Run `PythonApplication1.py` with Python. You should see results like the followi
9494

9595
:::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.":::
9696

97+
## Create a sample python app with re-authentication
98+
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.
99+
100+
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 EntraID user.
101+
102+
```python
103+
import time
104+
import logging
105+
import redis
106+
from azure.identity import DefaultAzureCredential
107+
108+
scope = "https://redis.azure.com/.default"
109+
host = "<Your Host Name>"
110+
port = 6380
111+
user_name = "<Your Username>"
112+
113+
def re_authentication():
114+
_LOGGER = logging.getLogger(__name__)
115+
cred = DefaultAzureCredential()
116+
token = cred.get_token(scope)
117+
r = redis.Redis(host=host,
118+
port=port,
119+
ssl=True, # ssl connection is required.
120+
username=user_name,
121+
password=token.token,
122+
decode_responses=True)
123+
max_retry = 3
124+
for index in range(max_retry):
125+
try:
126+
if _need_refreshing(token):
127+
_LOGGER.info("Refreshing token...")
128+
tmp_token = cred.get_token(scope)
129+
if tmp_token:
130+
token = tmp_token
131+
r.execute_command("AUTH", user_name, token.token)
132+
result = r.ping()
133+
print("Ping returned : " + str(result))
134+
135+
result = r.set("Message", "Hello!, The cache is working with Python!")
136+
print("SET Message returned : " + str(result))
137+
138+
result = r.get("Message")
139+
print("GET Message returned : " + result)
140+
141+
result = r.client_list()
142+
print("CLIENT LIST returned : ")
143+
for c in result:
144+
print(f"id : {c['id']}, addr : {c['addr']}")
145+
break
146+
except redis.ConnectionError:
147+
_LOGGER.info("Connection lost. Reconnecting.")
148+
token = cred.get_token(scope)
149+
r = redis.Redis(host=host,
150+
port=port,
151+
ssl=True, # ssl connection is required.
152+
username=user_name,
153+
password=token.token,
154+
decode_responses=True)
155+
except Exception:
156+
_LOGGER.info("Unknown failures.")
157+
break
158+
159+
160+
def _need_refreshing(token, refresh_offset=300):
161+
return not token or token.expires_on - time.time() < refresh_offset
162+
163+
if __name__ == '__main__':
164+
re_authentication()
165+
```
166+
167+
Run `PythonApplication2.py` with Python. You should see results like the following example:
168+
169+
:::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.":::
170+
171+
Unlike the first example, If your token has expired, this example will automatically refersh it.
172+
97173
## [Access Key Authentication](#tab/accesskey)
98174
[!INCLUDE [redis-cache-create](includes/redis-cache-access-keys.md)]
99175

@@ -112,9 +188,6 @@ True
112188
b'bar'
113189
```
114190

115-
> [!IMPORTANT]
116-
> 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.
117-
118191
## Create a Python sample app
119192

120193
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`.
@@ -135,7 +208,7 @@ result = r.set("Message", "Hello!, The cache is working with Python!")
135208
print("SET Message returned : " + str(result))
136209

137210
result = r.get("Message")
138-
print("GET Message returned : " + result.decode("utf-8"))
211+
print("GET Message returned : " + result)
139212

140213
result = r.client_list()
141214
print("CLIENT LIST returned : ")

0 commit comments

Comments
 (0)