Quickstart: Use Azure Cache for Redis with a Python app

In this quickstart, you incorporate Azure Cache for Redis into a Python script for access to a secure, dedicated cache that is accessible from any application in Azure.

Skip to the code

This article describes how to create a Python app and then modify the code to end up with a working sample app.

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

Prerequisites

Create a cache

  1. To create a cache, sign in to the Azure portal. On the portal menu, select Create a resource.

    Sceenshot that shows the Create a resource option highlighted on the left navigation pane in the Azure portal.

  2. On the Get Started pane, enter Azure Cache for Redis in the search bar. In the search results, find Azure Cache for Redis, and then select Create.

    Screenshot that shows Azure Marketplace with Azure Cache for Redis in the search box, and the Create button is highlighted.

  3. On the New Redis Cache pane, on the Basics tab, configure the following settings for your cache:

    Setting Action Description
    Subscription Select your Azure subscription. The subscription to use to create the new instance of Azure Cache for Redis.
    Resource group Select a resource group, or select Create new and enter a new resource group name. A name for the resource group in which to create your cache and other resources. By putting all your app resources in one resource group, you can easily manage or delete them together.
    DNS name Enter a unique name. The cache name must be a string of 1 to 63 characters that contains only numbers, letters, and hyphens. The name must start and end with a number or letter, and it can't contain consecutive hyphens. Your cache instance's host name is \<DNS name>.redis.cache.windows.net.
    Location Select a location. An Azure region that is near other services that use your cache.
    Cache SKU Select a SKU. The SKU determines the size, performance, and feature parameters that are available for the cache. For more information, see Azure Cache for Redis overview.
    Cache size Select a cache size. For more information, see Azure Cache for Redis overview.
  4. Select the Networking tab or select Next: Networking.

  5. On the Networking tab, select a connectivity method to use for the cache.

  6. Select the Advanced tab or select Next: Advanced.

  7. On the Advanced pane, verify or select an authentication method based on the following information:

    Screenshot showing the Advanced pane and the available options to select.

    • By default, for a new Basic, Standard, or Premium cache, Microsoft Entra Authentication is enabled and Access Keys Authentication is disabled.
    • For Basic or Standard caches, you can choose the selection for a non-TLS port.
    • For Standard and Premium caches, you can choose to enable availability zones. You can't disable availability zones after the cache is created.
    • For a Premium cache, configure the settings for non-TLS port, clustering, managed identity, and data persistence.

    Important

    For optimal security, we recommend that you use Microsoft Entra ID with managed identities to authorize requests against your cache if possible. Authorization by using Microsoft Entra ID and managed identities provides superior security and ease of use over shared access key authorization. For more information about using managed identities with your cache, see Use Microsoft Entra ID for cache authentication.

  8. (Optional) Select the Tags tab or select Next: Tags.

  9. (Optional) On the Tags tab, enter a tag name and value if you want to categorize your cache resource.

  10. Select the Review + create button.

    On the Review + create tab, Azure automatically validates your configuration.

  11. After the green Validation passed message appears, select Create.

A new cache deployment occurs over several minutes. You can monitor the progress of the deployment on the Azure Cache for Redis Overview pane. When Status displays Running, the cache is ready to use.

Install the redis-py library

Redis-py is a Python interface to Azure Cache for Redis. Use the Python packages tool pip to install the redis-py package at a command line.

The following example uses pip3 for Python 3 to install redis-py on Windows 11 in an Administrator Command Prompt window.

Screenshot of a terminal showing an install of redis-py interface to Azure Cache for Redis.

Create a Python script to access your cache

Create a Python script that uses either Microsoft Entra ID or access keys to connect to Azure Cache for Redis. We recommend that you use Microsoft Entra ID.

Enable Microsoft Entra ID authentication on your cache

For an existing cache, first check to see if Microsoft Entra authentication is enabled. If it's not, complete the following steps to enable Microsoft Entra authentication. We recommend that you use Microsoft Entra ID for authentication in your applications.

  1. In the Azure portal, select the Azure Cache for Redis instance where you'd like to use Microsoft Entra token-based authentication.

  2. On the service menu, under Settings, select Authentication.

  3. On the Authentication pane, check to see whether the Enable Microsoft Entra Authentication checkbox is selected. If it is, you can move on to the next section.

  4. Otherwise, select the Enable Microsoft Entra Authentication checkbox. Then, enter the name of a valid user. Select Save. The user name that you enter is automatically assigned the Data Owner Access Policy.

    You also can enter a managed identity or a service principal to connect to your cache.

    Screenshot that shows Authentication selected in the service menu and the Enable Microsoft Entra Authentication checkbox selected.

  5. In a dialog box, you're asked if you want to update your configuration, and you're informed that making the update takes several minutes to finish. Select Yes.

    Important

    When the enable operation is finished, the nodes in your cache reboot to load the new configuration. We recommend that you complete this operation during your standard maintenance window or outside your peak business hours. The process can take up to 30 minutes.

For information about using Microsoft Entra ID with the Azure CLI, see the identity reference pages.

Install Microsoft Authentication Library

Microsoft Authentication Library (MSAL) gets security tokens from the Microsoft identity platform to authenticate users.

To install MSAL:

  1. Install MSAL for Python.

  2. Install the Python Azure identity client library. The library uses MSAL to provide token authentication support.

    Install this library by using pip:

pip install azure-identity

Create a Python script by using Microsoft Entra ID

  1. Create a text file. Save the file as PythonApplication1.py.

  2. In PythonApplication1.py, add and modify the following script.

    In the script:

    • Replace <Your Host Name> with the value from your Azure Cache for Redis instance. Your host name has the form <DNS name>.redis.cache.windows.net.
    • Replace <Your Username> with the value for 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()
    
  3. Before you run your Python code in a terminal, authorize the terminal to use Microsoft Entra ID:

    azd auth login

  4. Run the PythonApplication1.py file by using Python. Verify that the output looks similar to this example:

    Screenshot of a terminal showing a Python script to test cache access.

Create a Python script by using reauthentication

A Microsoft Entra ID access token has a limited lifespan of approximately 75 minutes. To maintain a connection to your cache, you must refresh the token.

This example demonstrates how to refresh a token by using Python.

  1. Create a text file. Save the file as PythonApplication2.py.

  2. In PythonApplication2.py, add and modify the following script.

    In the script:

    • Replace <Your Host Name> with the value from your Azure Cache for Redis instance. Your host name has the form <DNS name>.redis.cache.windows.net.
    • Replace <Your Username> with the value for 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()
    
  3. Run the PythonApplication2.py file by using Python. Verify that the output looks similar to this example:

    Screenshot of a terminal showing a Python script to test cache access.

    Unlike in the preceding example, if your token expires, the code in this example automatically refreshes the token.

Clean up resources

If you want to continue to use the resources you created in this article, keep the resource group.

Otherwise, to avoid charges related to the resources, if you're finished using the resources, you can delete the Azure resource group that you created.

Warning

Deleting a resource group is irreversible. When you delete a resource group, all the resources in the resource group are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources. If you created the resources inside an existing resource group that has resources you want to keep, you can delete each resource individually instead of deleting the resource group.

Delete a resource group

  1. Sign in to the Azure portal, and then select Resource groups.

  2. Select the resource group to delete.

    If there are many resource groups, in Filter for any field, enter the name of the resource group you created to complete this article. In the list of search results, select the resource group.

    Screenshot that shows a list of resource groups to choose from to delete.

  3. Select Delete resource group.

  4. In the Delete a resource group pane, enter the name of your resource group to confirm, and then select Delete.

    Screenshot that shows a box that requires entering the resource name to confirm deletion.

Within a few moments, the resource group and all of its resources are deleted.