py-consul: Python Client for Consul

1.7.1 · active · verified Sun Apr 12

py-consul is an actively maintained Python client for Hashicorp Consul, enabling interaction with its Key/Value store, service discovery, health checks, and ACLs. It provides both synchronous and asynchronous (asyncio-based) interfaces. The library is currently at version 1.7.1 and releases occur periodically to address bug fixes, introduce new features, and maintain compatibility with newer Python and Consul versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `py-consul` client and perform basic Key/Value store operations such as setting, retrieving, and listing entries. It also includes an example of service registration using the agent API (commented out by default) and shows how to handle Consul's byte string values.

import consul
import os

# Configure Consul client (defaults to localhost:8500)
# Use environment variable CONSUL_HTTP_ADDR for production setup
consul_host = os.environ.get('CONSUL_HTTP_ADDR', '127.0.0.1')
consul_port = int(os.environ.get('CONSUL_HTTP_PORT', '8500'))
consul_token = os.environ.get('CONSUL_HTTP_TOKEN', None)

c = consul.Consul(host=consul_host, port=consul_port, token=consul_token)

# --- Key-Value Store Operations ---

# 1. Put a key-value pair
success = c.kv.put('my-app/config/greeting', 'Hello, Consul!')
if success:
    print("Key 'my-app/config/greeting' set successfully.")

# 2. Get a key-value pair
index, data = c.kv.get('my-app/config/greeting')
if data:
    value = data['Value'].decode('utf-8') # Value is bytes, needs decoding
    print(f"Retrieved key: {data['Key']}, Value: {value}, ModifyIndex: {data['ModifyIndex']}")
else:
    print("Key 'my-app/config/greeting' not found.")

# 3. List keys under a prefix
index, keys = c.kv.get('my-app/config/', recurse=True)
if keys:
    print("\nKeys under 'my-app/config/':")
    for item in keys:
        key = item['Key']
        value = item['Value'].decode('utf-8') if item['Value'] else None
        print(f"  - {key}: {value}")
else:
    print("\nNo keys found under 'my-app/config/'.")

# --- Service Registration (Agent API) ---
# This requires a running Consul agent
# try:
#     c.agent.service.register(
#         'my-service',
#         service_id='my-service-1',
#         address='127.0.0.1',
#         port=8000,
#         tags=['web', 'python'],
#         check=consul.check.HTTP('http://127.0.0.1:8000/health', interval='10s')
#     )
#     print("\nService 'my-service-1' registered.")
# except Exception as e:
#     print(f"\nFailed to register service: {e}")

view raw JSON →