Skip to main content

Connect with Python

Learn how to connect to an Aiven for Caching service using Python and the redis-py library.

Variables

Replace the following placeholders in the code sample with actual values from your service overview page:

VariableDescription
SERVICE_URIURI for the Aiven for Caching service connection

Prerequisites

To install the redis-pylibrary, run the following command:

pip install redis

Code

Create a file named main.py and insert the code below, substituting the placeholder with your Aiven for Caching URI:

import redis


def main():
redis_uri = 'REDIS_URI'
redis_client = redis.from_url(redis_uri)

redis_client.set('key', 'hello world')
key = redis_client.get('key').decode('utf-8')

print('The value of key is:', key)


if __name__ == '__main__':
main()

This code creates a key named key with the value hello world without an expiration. It then retrieves this key from the caching service and outputs its value.

Execute the script with:

python main.py
note

On some systems, using python3 is necessary to access Python 3 instead of the earlier Python 2.

Successful execution results in the following output:

The value of key is: hello world