Registry / http-networking / python-consul

python-consul

JSON →
library1.1.0pypypi✓ verified 25d ago

Python-consul is a client library for interacting with the Consul HTTP API. It provides a comprehensive set of features for service discovery, key-value storage, health checking, and session management. The library is currently at version 1.1.0 and is actively maintained with a moderate release cadence.

pip install python-consul
INSTALL
IMPORT
SIG · PYTHON-CONSUL
P
python-consul
http-networkingpythonv1.1.0
Install
2.2s avg
Import
374ms
Disk
20MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.384s · 21.4MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.2s · import 0.364s · 22MB
20MB installed
● package 20MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Consul
from consul import Consul

Initializes a Consul client, sets and retrieves a key-value pair, and registers a simple service. It demonstrates configuring the connection using environment variables and basic error handling.

import consul import os # Configure Consul connection details consul_host = os.environ.get('CONSUL_HOST', '127.0.0.1') consul_port = int(os.environ.get('CONSUL_PORT', '8500')) consul_scheme = os.environ.get('CONSUL_SCHEME', 'http') consul_token = os.environ.get('CONSUL_TOKEN', None) # For ACLs try: # Initialize Consul client c = consul.Consul( host=consul_host, port=consul_port, scheme=consul_scheme, token=consul_token ) # Example: Key-Value store operations key = "my_app/config/setting1" value = "hello_consul_world" # Put a value if c.kv.put(key, value): print(f"Successfully set key '{key}' to '{value}'") else: print(f"Failed to set key '{key}'") # Get a value index, data = c.kv.get(key) if data: retrieved_value = data['Value'].decode('utf-8') print(f"Retrieved key '{key}': '{retrieved_value}' (index: {index})") else: print(f"Key '{key}' not found.") # Example: Register a service (minimal) service_name = "my-test-service" service_id = "my-test-service-1" if c.agent.service.register(name=service_name, service_id=service_id, port=8000, tags=['python']): print(f"Service '{service_name}' registered successfully.") else: print(f"Failed to register service '{service_name}'.") # You can deregister later with: # c.agent.service.deregister(service_id) # print(f"Service '{service_name}' deregistered.") except Exception as e: print(f"An error occurred: {e}") print("Please ensure a Consul agent is running and accessible at " f"{consul_scheme}://{consul_host}:{consul_port}")
Debug
Known issues
breakingThe `ConsulResponse` object (returned by blocking queries) no longer has `.json()` or `.text` methods. These were removed in version 1.0.0 due to issues with blocking queries.
fix
Access data via the `data` tuple element returned by the API call, which directly contains the parsed JSON. For example, `index, data = c.kv.get('foo')` where `data` is the dictionary payload.
affects: >=1.0.0
breakingThe `acl.create` method now returns the ACL ID directly (as a string) instead of a dictionary containing the ID. Also, the `acl.clone` method was removed.
fix
Update call sites to expect a string return from `acl.create`. Refactor any usage of `acl.clone` to use `acl.create` with the desired parameters.
affects: >=1.0.0
breakingMany `ttl` arguments (e.g., in health check definitions or session creation) now expect a string (e.g., '10s') instead of an integer representing seconds.
fix
Convert integer `ttl` values to their string representations (e.g., `30` becomes `'30s'`).
affects: >=1.0.0
gotchaWhen performing blocking queries, it's crucial to pass the `index` returned from a previous call to subsequent calls. Failing to do so will result in immediate (non-blocking) queries, leading to busy-waiting or inefficient polling.
fix
Always capture the `index` value (e.g., `index, data = c.kv.get('foo')`) and pass it as the `index` argument for subsequent blocking calls (`index, new_data = c.kv.get('foo', index=index)`).
affects: all
gotchaIf your Consul server has Access Control Lists (ACLs) enabled, you must provide a valid `token` to relevant client methods (e.g., `c.kv.put('key', 'value', token='your-token')`) or during client initialization.
fix
Ensure `token` is passed either during `consul.Consul()` initialization or as an argument to specific API calls that require it.
affects: all
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'consul'
The 'python-consul' library is not installed in the current Python environment.
fix
pip install python-consul
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionRefusedError(111, 'Connection refused'))
The Consul agent is not running or is inaccessible at the specified host and port, preventing the client from establishing a connection.
fix
Ensure the Consul agent is running and accessible at the specified host and port. If necessary, configure the client with `c = consul.Consul(host='<ip>', port=<port>)`.
consul.exceptions.ConsulException: 404 Not Found
The requested resource, such as a key in the KV store or a service, does not exist in Consul.
fix
To check for key existence, retrieve it and check if the returned `data` is `None`: `index, data = c.kv.get('my_key'); if data is None: print('Key not found')`.
consul.exceptions.ConsulException: Get http://127.0.0.1:8500/v1/kv/mykey: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
The Consul agent did not respond within the configured timeout period, possibly due to network latency, an overloaded server, or the agent being slow.
fix
Increase the timeout when initializing the Consul client: `c = consul.Consul(timeout=10.0)`.
Upgrade
Version history
1.1.0latest on PyPI · released Jul 9, 2018
Audit
Dependencies
requestsrequiredUsed for making HTTP requests to the Consul API.
Agent activity
17 hits · last 30 days
node
6
Resources
python-consul — pip install python-consul · libregistry