title | description | ms.date | ms.topic | ms.devlang | ms.custom | zone_pivot_groups | appliesto | ||
---|---|---|---|---|---|---|---|---|---|
Quickstart: Use Azure Cache for Redis in Python | In this quickstart, you learn how to create a Python script that uses Azure Redis. | 07/09/2024 | quickstart | python | mvc, devx-track-python, mode-api, py-fresh-zinc, ignite-2024 | redis-type |
|
In this Quickstart, you incorporate Azure Managed Redis (preview) or Azure Cache for Redis into a Python script to have access to a secure, dedicated cache that is accessible from any application within Azure.
If you want to skip straight to the code, see the Python quickstart on GitHub.
- Azure subscription - create one for free
- Python 3
- For macOS or Linux, download from python.org.
- For Windows 11, use the Windows Store.
::: zone pivot="azure-managed-redis"
[!INCLUDE managed-redis-create]
::: zone-end
::: zone pivot="azure-cache-redis"
[!INCLUDE redis-cache-create]
::: zone-end
Redis-py is a Python interface to Redis. Use the Python packages tool, pip
, to install the redis-py
package from a command prompt.
The following example used pip3
for Python 3 to install redis-py
on Windows 11 from an Administrator command prompt.
:::image type="content" source="media/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.":::
::: zone pivot="azure-managed-redis"
Create a Python script to that uses either Microsoft Entra ID or access keys to connect to your Azure Managed Redis (preview) instance. We recommend you use Microsoft Entra ID.
[!INCLUDE cache-entra-access]
Install the Microsoft Authentication Library (MSAL). This library allows you to acquire security tokens from Microsoft identity to authenticate users.
You can use the Python Azure identity client library available that uses MSAL to provide token authentication support. Install this library using
pip
:
pipinstallazure-identity
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>.<region>.redis.azure.net
.Replace
<Your Username>
with the values from your Microsoft Entra ID user.importredisfromazure.identityimportDefaultAzureCredentialscope="https://redis.azure.com/.default"host="<Your Host Name>"port=10000user_name="<Your Username>"defhello_world(): cred=DefaultAzureCredential() token=cred.get_token(scope) r=redis.Redis(host=host, port=port, ssl=True, # ssl connection is required.username=user_name, password=token.token, decode_responses=True) result=r.ping() print("Ping returned : "+str(result)) result=r.set("Message", "Hello!, The cache is working with Python!") print("SET Message returned : "+str(result)) result=r.get("Message") print("GET Message returned : "+result) result=r.client_list() print("CLIENT LIST returned : ") forcinresult: print(f"id : {c['id']}, addr : {c['addr']}") if__name__=='__main__': hello_world()
Before you run your Python code from a Terminal, make sure you authorize the terminal for using Microsoft Entra ID.
azd auth login
Run
PythonApplication1.py
with Python. You should see results like the following example::::image type="content" source="media/python-get-started/cache-python-completed.png" alt-text="Screenshot of a terminal showing a Python script to test cache access.":::
Microsoft Entra ID access tokens have limited lifespans, averaging 75 minutes. In order to maintain a connection to your cache, you need to refresh the token. This example demonstrates how to do this using Python.
Create a new text file, add the following script. Then, save the file as
PythonApplication2.py
.Replace
<Your Host Name>
with the value from your Azure Managed Redis (preview) instance. Your host name is of the form<DNS name>.<region>.redis.azure.net
.Replace
<Your Username>
with the values from your Microsoft Entra ID user.importtimeimportloggingimportredisfromazure.identityimportDefaultAzureCredentialscope="https://redis.azure.com/.default"host="<Your Host Name>"port=10000user_name="<Your Username>"defre_authentication(): _LOGGER=logging.getLogger(__name__) cred=DefaultAzureCredential() token=cred.get_token(scope) r=redis.Redis(host=host, port=port, ssl=True, # ssl connection is required.username=user_name, password=token.token, decode_responses=True) max_retry=3forindexinrange(max_retry): try: if_need_refreshing(token): _LOGGER.info("Refreshing token...") tmp_token=cred.get_token(scope) iftmp_token: token=tmp_tokenr.execute_command("AUTH", user_name, token.token) result=r.ping() print("Ping returned : "+str(result)) result=r.set("Message", "Hello!, The cache is working with Python!") print("SET Message returned : "+str(result)) result=r.get("Message") print("GET Message returned : "+result) result=r.client_list() print("CLIENT LIST returned : ") forcinresult: print(f"id : {c['id']}, addr : {c['addr']}") breakexceptredis.ConnectionError: _LOGGER.info("Connection lost. Reconnecting.") token=cred.get_token(scope) r=redis.Redis(host=host, port=port, ssl=True, # ssl connection is required.username=user_name, password=token.token, decode_responses=True) exceptException: _LOGGER.info("Unknown failures.") breakdef_need_refreshing(token, refresh_offset=300): returnnottokenortoken.expires_on-time.time() <refresh_offsetif__name__=='__main__': re_authentication()
Run
PythonApplication2.py
with Python. You should see results like the following example::::image type="content" source="media/python-get-started/cache-python-completed.png" alt-text="Screenshot of a terminal showing a Python script to test cache access.":::
Unlike the first example, If your token expires, this example automatically refreshes it.
[!INCLUDE redis-cache-access-keys]
Run Python from the command line 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
.
>>>importredis>>>r=redis.Redis(host='<Your Host Name>', port=10000, password='<Your Access Key>', ssl=True) >>>r.set('foo', 'bar') True>>>r.get('foo') b'bar'
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>.<region>.redis.azure.net
.
importredismyHostname="<Your Host Name>"myPassword="<Your Access Key>"r=redis.Redis(host=myHostname, port=10000, password=myPassword, ssl=True) result=r.ping() print("Ping returned : "+str(result)) result=r.set("Message", "Hello!, The cache is working with Python!") print("SET Message returned : "+str(result)) result=r.get("Message") print("GET Message returned : "+result) result=r.client_list() print("CLIENT LIST returned : ") forcinresult: print(f"id : {c['id']}, addr : {c['addr']}")
Run PythonApplication1.py
with Python. You should see results like the following example:
:::image type="content" source="media/python-get-started/cache-python-completed.png" alt-text="Screenshot of a terminal showing a Python script to test cache access.":::
::: zone-end
::: zone pivot="azure-cache-redis"
Create a Python script to that uses either Microsoft Entra ID or access keys to connect to your Redis instance. We recommend you use Microsoft Entra ID.
[!INCLUDE cache-entra-access]
Install the Microsoft Authentication Library (MSAL). This library allows you to acquire security tokens from Microsoft identity to authenticate users.
You can use the Python Azure identity client library available that uses MSAL to provide token authentication support. Install this library using
pip
:
pipinstallazure-identity
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 Entra ID user.importredisfromazure.identityimportDefaultAzureCredentialscope="https://redis.azure.com/.default"host="<Your Host Name>"port=6380user_name="<Your Username>"defhello_world(): cred=DefaultAzureCredential() token=cred.get_token(scope) r=redis.Redis(host=host, port=port, ssl=True, # ssl connection is required.username=user_name, password=token.token, decode_responses=True) result=r.ping() print("Ping returned : "+str(result)) result=r.set("Message", "Hello!, The cache is working with Python!") print("SET Message returned : "+str(result)) result=r.get("Message") print("GET Message returned : "+result) result=r.client_list() print("CLIENT LIST returned : ") forcinresult: print(f"id : {c['id']}, addr : {c['addr']}") if__name__=='__main__': hello_world()
Before you run your Python code from a Terminal, make sure you authorize the terminal for using Microsoft Entra ID.
azd auth login
Run
PythonApplication1.py
with Python. You should see results like the following example::::image type="content" source="media/python-get-started/cache-python-completed.png" alt-text="Screenshot of a terminal showing a Python script to test cache access.":::
Microsoft Entra ID access tokens have limited lifespans, averaging 75 minutes. In order to maintain a connection to your cache, you need to refresh the token. This example demonstrates how to do this using Python.
Create a new text file, add the following script. Then, 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 Entra ID user.importtimeimportloggingimportredisfromazure.identityimportDefaultAzureCredentialscope="https://redis.azure.com/.default"host="<Your Host Name>"port=6380user_name="<Your Username>"defre_authentication(): _LOGGER=logging.getLogger(__name__) cred=DefaultAzureCredential() token=cred.get_token(scope) r=redis.Redis(host=host, port=port, ssl=True, # ssl connection is required.username=user_name, password=token.token, decode_responses=True) max_retry=3forindexinrange(max_retry): try: if_need_refreshing(token): _LOGGER.info("Refreshing token...") tmp_token=cred.get_token(scope) iftmp_token: token=tmp_tokenr.execute_command("AUTH", user_name, token.token) result=r.ping() print("Ping returned : "+str(result)) result=r.set("Message", "Hello!, The cache is working with Python!") print("SET Message returned : "+str(result)) result=r.get("Message") print("GET Message returned : "+result) result=r.client_list() print("CLIENT LIST returned : ") forcinresult: print(f"id : {c['id']}, addr : {c['addr']}") breakexceptredis.ConnectionError: _LOGGER.info("Connection lost. Reconnecting.") token=cred.get_token(scope) r=redis.Redis(host=host, port=port, ssl=True, # ssl connection is required.username=user_name, password=token.token, decode_responses=True) exceptException: _LOGGER.info("Unknown failures.") breakdef_need_refreshing(token, refresh_offset=300): returnnottokenortoken.expires_on-time.time() <refresh_offsetif__name__=='__main__': re_authentication()
Run
PythonApplication2.py
with Python. You should see results like the following example::::image type="content" source="media/python-get-started/cache-python-completed.png" alt-text="Screenshot of a terminal showing a Python script to test cache access.":::
Unlike the first example, If your token expires, this example automatically refreshes it.
[!INCLUDE redis-access-key-alert]
[!INCLUDE redis-cache-access-keys]
Run Python from the command line 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
.
>>>importredis>>>r=redis.Redis(host='<Your Host Name>', port=6380, db=0, password='<Your Access Key>', ssl=True) >>>r.set('foo', 'bar') True>>>r.get('foo') b'bar'
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
.
importredismyHostname="<Your Host Name>"myPassword="<Your Access Key>"r=redis.Redis(host=myHostname, port=6380, password=myPassword, ssl=True) result=r.ping() print("Ping returned : "+str(result)) result=r.set("Message", "Hello!, The cache is working with Python!") print("SET Message returned : "+str(result)) result=r.get("Message") print("GET Message returned : "+result) result=r.client_list() print("CLIENT LIST returned : ") forcinresult: print(f"id : {c['id']}, addr : {c['addr']}")
Run PythonApplication1.py
with Python. You should see results like the following example:
:::image type="content" source="media/python-get-started/cache-python-completed.png" alt-text="Screenshot of a terminal showing a Python script to test cache access.":::
::: zone-end
[!INCLUDE cache-delete-resource-group]