Skip to main content

Connect with Python

Connect to the Aiven for Valkey service using Python with the valkey-py library. valkey-py is a Python interface specifically designed for the Valkey key-value store.

Variables

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

VariableDescription
SERVICE_URIURI for the Aiven for Valkey service connection

Prerequisites

Install the valkey-py library with optional performance enhancements from hiredis by running the following commands:

pip install valkey
pip install "valkey[hiredis]"

Set up and run

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

    import valkey

    def main():
    valkey_uri = 'SERVICE_URI' # Replace 'VALKEY_URI' with your actual Valkey service URI
    valkey_client = valkey.from_url(service_uri)

    valkey_client.set('key', 'hello world')
    key = valkey_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 Valkey service and outputs its value.

  2. Run the script using the following command:

    python main.py
    note

    Use python3 instead of python on systems where it defaults to Python 2.

    Successful execution results in the following output:

    The value of key is: hello world