Valkey Python Client

6.1.1 · active · verified Thu Apr 09

Valkey-py is a high-performance Python client for Valkey, a robust open-source (BSD) key/value datastore. Forked from redis-py, it supports a variety of workloads including caching, message queues, and acting as a primary database. The library is actively maintained with frequent releases, including release candidates for upcoming versions.

Warnings

Install

Imports

Quickstart

Connects to a Valkey server, pings it to verify the connection, then sets and retrieves a simple string key. It demonstrates using `from_url` for flexible connection and `decode_responses=True` for working with strings instead of bytes.

import valkey
import os

def main():
    # Connect to Valkey (defaults to localhost:6379)
    # Use VALKEY_URL environment variable for production configurations
    valkey_url = os.environ.get('VALKEY_URL', 'valkey://localhost:6379')
    r = valkey.from_url(valkey_url, decode_responses=True)

    try:
        r.ping()
        print(f"Connected to Valkey at {valkey_url}")

        # Set a key-value pair
        r.set('mykey', 'Hello, Valkey!')
        print("Set 'mykey' to 'Hello, Valkey!'")

        # Get the value back
        value = r.get('mykey')
        print(f"Value of 'mykey': {value}")

    except valkey.exceptions.ConnectionError as e:
        print(f"Could not connect to Valkey: {e}")
    finally:
        # For async clients, explicitly await aclose()
        # For sync clients, connection is managed by pool
        pass

if __name__ == '__main__':
    main()

view raw JSON →