Python Consul 2 Client (Abandoned)

0.1.5 · abandoned · verified Fri Apr 17

python-consul2 is a Python client library for interacting with Consul (http://www.consul.io/), providing an interface for its KV store, agent, and catalog APIs. This library is a fork of python-consul. Its current version is 0.1.5, and it appears to be unmaintained, with no releases or commits since 2018.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Consul client, put and get key-value pairs from the KV store, and list keys by prefix. Ensure a Consul agent is running and accessible at the specified host and port (default: localhost:8500).

import os
import consul

# Configuration for Consul connection
CONSUL_HOST = os.environ.get('CONSUL_HOST', 'localhost')
CONSUL_PORT = int(os.environ.get('CONSUL_PORT', '8500'))

try:
    # Initialize Consul client
    c = consul.Consul(host=CONSUL_HOST, port=CONSUL_PORT)

    # Example 1: Put a key-value pair
    key = 'my-app/config/feature-flag'
    value = 'true'
    success = c.kv.put(key, value)
    if success:
        print(f"Successfully set key '{key}' to '{value}'")

    # Example 2: Get a key-value pair
    index, data = c.kv.get(key)
    if data:
        retrieved_value = data['Value'].decode('utf-8')
        print(f"Retrieved key '{key}': '{retrieved_value}'")
    else:
        print(f"Key '{key}' not found.")

    # Example 3: List keys under a prefix
    index, data = c.kv.get('my-app/', recurse=True)
    if data:
        print(f"Keys under 'my-app/':")
        for item in data:
            print(f"  - {item['Key']}: {item['Value'].decode('utf-8') if item['Value'] else 'N/A'}")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Ensure Consul agent is running and accessible at {CONSUL_HOST}:{CONSUL_PORT}")

view raw JSON →