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
Copy file name to clipboardExpand all lines: articles/azure-cache-for-redis/cache-python-get-started.md
+80-7Lines changed: 80 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -58,9 +58,9 @@ import redis
58
58
from azure.identity import DefaultAzureCredential
59
59
60
60
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>"
64
64
65
65
66
66
defhello_world():
@@ -94,6 +94,82 @@ Run `PythonApplication1.py` with Python. You should see results like the followi
94
94
95
95
:::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.":::
96
96
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
+
defre_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 inrange(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
+
exceptException:
156
+
_LOGGER.info("Unknown failures.")
157
+
break
158
+
159
+
160
+
def_need_refreshing(token, refresh_offset=300):
161
+
returnnot 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.
> 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
-
118
191
## Create a Python sample app
119
192
120
193
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!")
135
208
print("SET Message returned : "+str(result))
136
209
137
210
result = r.get("Message")
138
-
print("GET Message returned : "+ result.decode("utf-8"))
0 commit comments