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:
Variable | Description |
---|---|
SERVICE_URI | URI 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
-
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 valuehello world
without an expiration. It then retrieves this key from the Valkey service and outputs its value. -
Run the script using the following command:
python main.py
noteUse
python3
instead ofpython
on systems where it defaults to Python 2.Successful execution results in the following output:
The value of key is: hello world
Related Pages
- For additional information about
valkey-py
, see the valkey-py GitHub Repository.