python-etcd: etcd v2 Client

0.4.5 · abandoned · verified Wed Apr 15

A Python client library for etcd. This library specifically targets and supports the etcd v2 API. The last release (0.4.5) was in March 2017, and it is no longer actively maintained. It has no stated release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the etcd client, write a key-value pair, read it back, set a TTL, and delete a key. It assumes an etcd v2 server is running and accessible at the specified host and port. Remember this client is ONLY compatible with etcd v2.

import etcd
import os

# Configure etcd host and port (defaults to localhost:2379 for etcd v2)
# Replace with your etcd v2 cluster address
etcd_host = os.environ.get('ETCD_HOST', '127.0.0.1')
etcd_port = int(os.environ.get('ETCD_PORT', 2379))

try:
    # Initialize client for etcd v2
    client = etcd.Client(host=etcd_host, port=etcd_port)
    print(f"Connected to etcd v2 at {etcd_host}:{etcd_port}")

    # Write a key-value pair
    client.write('/mykey', 'myvalue')
    print("Wrote '/mykey': 'myvalue'")

    # Read the value back
    result = client.read('/mykey')
    print(f"Read '/mykey': {result.value}")

    # Update a key with a TTL (Time To Live)
    client.write('/tempkey', 'tempvalue', ttl=5)
    print("Wrote '/tempkey' with a 5-second TTL")

    # Delete a key
    client.delete('/mykey')
    print("Deleted '/mykey'")

except etcd.EtcdException as e:
    print(f"An etcd error occurred: {e}")
except ConnectionRefusedError:
    print(f"Connection to etcd v2 at {etcd_host}:{etcd_port} refused. Is etcd v2 running?")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →