Skip to main content

Connecting with Python

This guide explains how to connect a Python application to a Valkey database using the redis library. It walks through the required setup, configuration, and execution of a simple Valkey command.

Variables

To connect to Valkey, the following parameters are needed. You can find these values in the Elestio Valkey service overview.

Variable

Description

Purpose

HOST

Valkey hostname (from Elestio service overview)

Address of the Valkey server.

PORT

Valkey port (from Elestio service overview)

Port used to connect to Valkey. The default is 6379.

PASSWORD

Valkey password (from Elestio service overview)

Authentication credential for the Valkey connection.

These values can usually be found in the Elestio service overview details as shown in the image below, make sure to take a copy of these details and add it to the code moving ahead.

Screenshot 2025-07-04 at 4.12.37 PM.jpg

Prerequisites

Install Python and pip

  • Check if Python is installed by running:

python3 --version
  • If not installed, download and install it from python.org.

  • Check pip (Python package installer):

pip --version

Install the redis Package

Install the official redis library using pip:

pip install redis

Code

Create a file named valkey.py and paste the following code:

import redis

config = {
    "host": "HOST",
    "port": PORT,  # Example: 6379
    "password": "PASSWORD",
    "decode_responses": True
}

try:
    client = redis.Redis(**config)
    client.set("testKey", "Hello Valkey")
    value = client.get("testKey")
    print("Connected to Valkey")
    print("Retrieved value:", value)

except redis.RedisError as err:
    print("Valkey connection or operation failed:", err)

To execute the script, open the terminal or command prompt and navigate to the directory where valkey.py is located. Once in the correct directory, run the script with the command:

python3 redis.py

If everything is set up correctly, the output will be:

Connected to Valkey  
Retrieved value: Hello Valkey