Skip to content

Latest commit

 

History

History
480 lines (335 loc) · 18.6 KB

python-get-started.md

File metadata and controls

480 lines (335 loc) · 18.6 KB
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
✅ Azure Managed Redis
✅ Azure Cache for Redis

Quickstart: Use Azure Redis in Python

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.

Skip to the code on GitHub

If you want to skip straight to the code, see the Python quickstart on GitHub.

Prerequisites

::: zone pivot="azure-managed-redis"

Create an Azure Managed Redis (preview) instance

[!INCLUDE managed-redis-create]

::: zone-end

::: zone pivot="azure-cache-redis"

Create an Azure Cache for Redis instance

[!INCLUDE redis-cache-create]

::: zone-end

Install redis-py library

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 access your cache

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

  1. Install the Microsoft Authentication Library (MSAL). This library allows you to acquire security tokens from Microsoft identity to authenticate users.

  2. You can use the Python Azure identity client library available that uses MSAL to provide token authentication support. Install this library using pip:

pip install azure-identity

Create a Python script using Microsoft Entra ID

  1. Create a new text file, add the following script, and save the file as PythonApplication1.py.

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

  3. Replace <Your Username> with the values from your Microsoft Entra ID user.

    import redis
    from azure.identity import DefaultAzureCredential
    
    scope = "https://redis.azure.com/.default"
    host = "<Your Host Name>"
    port = 10000
    user_name = "<Your Username>"
    
    
    def hello_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 : ")
        for c in result:
            print(f"id : {c['id']}, addr : {c['addr']}")
    
    if __name__ == '__main__':
        hello_world()
  4. Before you run your Python code from a Terminal, make sure you authorize the terminal for using Microsoft Entra ID.

    azd auth login

  5. 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.":::

Create a Python script using reauthentication

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.

  1. Create a new text file, add the following script. Then, save the file as PythonApplication2.py.

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

  3. Replace <Your Username> with the values from your Microsoft Entra ID user.

    import time
    import logging
    import redis
    from azure.identity import DefaultAzureCredential
    
    scope = "https://redis.azure.com/.default"
    host = "<Your Host Name>"
    port = 10000
    user_name = "<Your Username>"
    
    def re_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 = 3
        for index in range(max_retry):
            try:
                if _need_refreshing(token):
                    _LOGGER.info("Refreshing token...")
                    tmp_token = cred.get_token(scope)
                    if tmp_token:
                        token = tmp_token
                    r.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 : ")
                for c in result:
                    print(f"id : {c['id']}, addr : {c['addr']}")
                break
            except redis.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)
            except Exception:
                _LOGGER.info("Unknown failures.")
                break
    
    
    def _need_refreshing(token, refresh_offset=300):
        return not token or token.expires_on - time.time() < refresh_offset
    
    if __name__ == '__main__':
        re_authentication()
  4. 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]

Read and write to the cache from the command line

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.

>>> import redis
>>> 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 Python script using access keys

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.

import redis

myHostname = "<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 : ")
for c in result:
    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 access your cache

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

  1. Install the Microsoft Authentication Library (MSAL). This library allows you to acquire security tokens from Microsoft identity to authenticate users.

  2. You can use the Python Azure identity client library available that uses MSAL to provide token authentication support. Install this library using pip:

pip install azure-identity

Create a Python script using Microsoft Entra ID

  1. Create a new text file, add the following script, and save the file as PythonApplication1.py.

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

  3. Replace <Your Username> with the values from your Microsoft Entra ID user.

    import redis
    from azure.identity import DefaultAzureCredential
    
    scope = "https://redis.azure.com/.default"
    host = "<Your Host Name>"
    port = 6380
    user_name = "<Your Username>"
    
    
    def hello_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 : ")
        for c in result:
            print(f"id : {c['id']}, addr : {c['addr']}")
    
    if __name__ == '__main__':
        hello_world()
  4. Before you run your Python code from a Terminal, make sure you authorize the terminal for using Microsoft Entra ID.

    azd auth login

  5. 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.":::

Create a Python script using reauthentication

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.

  1. Create a new text file, add the following script. Then, save the file as PythonApplication2.py.

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

  3. Replace <Your Username> with the values from your Microsoft Entra ID user.

    import time
    import logging
    import redis
    from azure.identity import DefaultAzureCredential
    
    scope = "https://redis.azure.com/.default"
    host = "<Your Host Name>"
    port = 6380
    user_name = "<Your Username>"
    
    def re_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 = 3
        for index in range(max_retry):
            try:
                if _need_refreshing(token):
                    _LOGGER.info("Refreshing token...")
                    tmp_token = cred.get_token(scope)
                    if tmp_token:
                        token = tmp_token
                    r.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 : ")
                for c in result:
                    print(f"id : {c['id']}, addr : {c['addr']}")
                break
            except redis.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)
            except Exception:
                _LOGGER.info("Unknown failures.")
                break
    
    
    def _need_refreshing(token, refresh_offset=300):
        return not token or token.expires_on - time.time() < refresh_offset
    
    if __name__ == '__main__':
        re_authentication()
  4. 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]

Read and write to the cache from the command line

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.

>>> import redis
>>> 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 Python script using access keys

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.

import redis

myHostname = "<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 : ")
for c in result:
    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]

Related content