Couchbase Python Client
The Couchbase Python Client (SDK) is an official library for interacting with Couchbase Server and Couchbase Capella. It provides functionalities for data operations (CRUD), querying (N1QL, FTS, Analytics, Vector Search), and cluster management. The current major version is 4.x, built on a high-performance C++ backend. The library maintains an active development cycle with regular minor and patch releases delivering new features, improvements, and bug fixes.
Warnings
- breaking Migration from SDK 2.x to SDK 3.x/4.x involves significant API changes, including the removal of the `Document` class (now `Result` objects are returned) and the introduction of `Collections` and `Scopes` for data organization.
- breaking The Couchbase Python SDK 4.x switched its backend from `libcouchbase` to `Couchbase++`. While the API surface aims for compatibility with SDK 3.x, code relying on undocumented internal details might break.
- breaking When using the `txcouchbase` API for Twisted integration in SDK 4.x, the `txcouchbase` package *must* be imported before importing the Twisted reactor to ensure the `asyncio` reactor is properly installed.
- gotcha Couchbase connection objects are not fork-safe. If using multiprocessing (e.g., with Gunicorn/uWSGI), ensure that `Cluster.connect()` (or similar connection initialization) is called *after* a child process has forked, not in the parent process.
- gotcha Python 3.11.5+ on Windows uses OpenSSL 3.0. Couchbase Python SDK versions below 4.1.9 were built against OpenSSL 1.1, potentially causing `ImportError: DLL load failed while importing pycbc_core`.
- deprecated The Couchbase Python SDK is dropping support for older Python versions as they reach their End-of-Life (EOL). Python 3.8 wheels are no longer provided, and Python 3.9 wheels will be removed in a future release (Python 3.9 reaches EOL in October 2025).
- gotcha Direct configuration of KV/data service connection pooling is not currently supported, and options like `max_http_connections` passed to the C++ core are a no-op for these services.
Install
-
pip install couchbase
Imports
- Cluster
from couchbase.cluster import Cluster
- ClusterOptions
from couchbase.options import ClusterOptions
- PasswordAuthenticator
from couchbase.auth import PasswordAuthenticator
- QueryOptions
from couchbase.options import QueryOptions
- acouchbase.cluster.Cluster
from acouchbase.cluster import Cluster, get_event_loop
- txcouchbase
import txcouchbase from twisted.internet import reactor from txcouchbase.cluster import TxCluster
Quickstart
import os
from couchbase.cluster import Cluster, ClusterOptions
from couchbase.auth import PasswordAuthenticator
from couchbase.exceptions import CouchbaseException
# Get connection details from environment variables for security
CONNECTION_STRING = os.environ.get('CB_CONNECTION_STRING', 'couchbase://localhost')
USERNAME = os.environ.get('CB_USERNAME', 'Administrator')
PASSWORD = os.environ.get('CB_PASSWORD', 'password')
BUCKET_NAME = os.environ.get('CB_BUCKET_NAME', 'default')
def main():
cluster = None
try:
# Connect to Couchbase Cluster
auth = PasswordAuthenticator(USERNAME, PASSWORD)
cluster_options = ClusterOptions(auth)
cluster = Cluster(CONNECTION_STRING, cluster_options)
# Wait for the cluster to be ready (optional but good practice)
# cluster.wait_until_ready(timedelta(seconds=5))
# Get a bucket and default collection
bucket = cluster.bucket(BUCKET_NAME)
collection = bucket.default_collection()
# Store a document
key = 'user:123'
value = {'name': 'Alice', 'age': 30, 'city': 'New York'}
result = collection.upsert(key, value)
print(f"Upserted document '{key}', CAS: {result.cas}")
# Retrieve the document
get_result = collection.get(key)
print(f"Retrieved document '{key}': {get_result.content_as[dict]}")
# Update a field in the document
updated_value = get_result.content_as[dict]
updated_value['age'] = 31
update_result = collection.upsert(key, updated_value)
print(f"Updated document '{key}', new CAS: {update_result.cas}")
# Delete the document
collection.remove(key)
print(f"Removed document '{key}'")
except CouchbaseException as e:
print(f"Couchbase Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
if cluster:
# Close the cluster connection (important for resource management)
cluster.disconnect()
if __name__ == '__main__':
main()