Registry / devops / py-consul

py-consul

JSON →
library1.7.1pypypi✓ verified 26d ago

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.

pip install py-consul
INSTALL
IMPORT
SIG · PY-CONSUL
P
py-consul
devopspythonv1.7.1
Install
2.1s avg
Import
365ms
Disk
20MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v1.7.1 · 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.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.380s · 21.4MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 2.1s · import 0.350s · 22MB
20MB installed
● package 20MB
Code
Verified usage

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

Consul
✓ from consul import Consul
✗ import consul; client = consul.Consul()
While 'import consul' works, 'from consul import Consul' is the idiomatic way to import the main client class.
aio
✓ from consul import aio
✗ from consul.aio import Consul
The recommended pattern for the async client is to import the 'aio' module and instantiate 'aio.Consul()', as shown in official examples.

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}")
Debug
Known issues
breakingPython 3.8 and older versions are no longer supported. Version 1.7.0 and later explicitly require Python 3.10 or higher.
fix
Upgrade your Python environment to 3.10 or newer. If you must use an older Python, pin `py-consul` to `<1.7.0` (e.g., `py-consul<1.7`).
affects: >=1.7.0
breakingThe ACL endpoint was moved from `consul.acl` to `consul.acl.token` in version 1.5.0, aligning with upstream Consul API changes.
fix
Update your code to use `client.acl.token` for ACL operations instead of `client.acl`. For example, `c.acl.token.create()` instead of `c.acl.create()`.
affects: >=1.5.0
gotchaValues 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.
fix
Always decode the `Value` field from the dictionary returned by `c.kv.get()` and `c.kv.get(recurse=True)`. Example: `data['Value'].decode('utf-8')`.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'consul'
The `py-consul` library is not installed or the Python interpreter cannot find the installed package.
fix
Ensure the `py-consul` package is installed in your active Python environment using pip: `pip install py-consul`.
consul.base.ACLPermissionDenied: rpc error making call: Permission denied
The Consul agent requires an ACL token for the requested operation, but no token was provided or the provided token lacks the necessary permissions.
fix
Pass a valid ACL token when initializing the Consul client or with the specific API call. For example: `c = consul.Consul(token='your_acl_token')` or `c.kv.get('foo', token='your_acl_token')`.
KeyError: 'your_key_name'
You are attempting to access a key in Consul's Key/Value store or a dictionary-like response from the API that does not exist.
fix
Verify that the key exists before accessing it, typically by checking the return value for `None` or using dictionary's `.get()` method. Example: `index, data = c.kv.get('your_key_name'); if data: print(data['Value'])` or `value = data.get('Value')`.
AttributeError: module 'asyncio' has no attribute 'coroutine'
This error often occurs when using the `asyncio` client with older Python versions (prior to 3.8) or if code still uses the deprecated `@asyncio.coroutine` decorator, which was removed in Python 3.11.
fix
Upgrade to a newer Python version (3.8+) and update your asynchronous code to use `async def` and `await` keywords instead of `@asyncio.coroutine` and `yield from`. Ensure you are using a `py-consul` version compatible with your Python runtime. For example: `async def go(): c = consul.aio.Consul(); await c.kv.put('foo', 'bar')`.
Upgrade
Version history
1.7.1latest on PyPI · released Nov 24, 2025
Audit
Dependencies
aiohttpoptionalRequired for the `consul.aio` (asyncio) client.
Agent activity
16 hits · last 30 days
node
12
Resources
py-consul — pip install py-consul · libregistry