py-consul: Python Client for Consul
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
- breaking Python 3.8 and older versions are no longer supported. Version 1.7.0 and later explicitly require Python 3.10 or higher.
- breaking The ACL endpoint was moved from `consul.acl` to `consul.acl.token` in version 1.5.0, aligning with upstream Consul API changes.
- gotcha Values retrieved from Consul's Key/Value store are always returned as byte strings. Failing to decode them (e.g., using `.decode('utf-8')`) can lead to unexpected `TypeError` or incorrect data handling.
Install
-
pip install py-consul
Imports
- Consul
from consul import Consul
- aio
from consul import aio
Quickstart
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}")