Registry / database / couchbase

couchbase

JSON →
library4.6.3pypypi✓ verified 22d ago

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.

pip install couchbase
INSTALL
IMPORT
SIG · COUCHBASE
C
couchbase
databasepythonv4.6.3
Install
2.1s avg
Import
890ms
Disk
47MB
Pass rate
8/ 10
Env Coverage8 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.6.3 · 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
glibc
py 3.10
✓ —
✓ 2.2s
py 3.11
✓ —
✓ 2.3s
py 3.12
✓ —
✓ 2.1s
py 3.13
✓ —
✓ 2s
py 3.9
✕ build_error
✕ build_error
47MB installed
● package 47MB
Code
Verified usage

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

Cluster
from couchbase.cluster import Cluster
from couchbase.bucket import Cluster
The primary `Cluster` object for synchronous operations is now found directly under `couchbase.cluster`. Older SDKs might have had different paths.
ClusterOptions
from couchbase.options import ClusterOptions
from couchbase.cluster import ClusterOptions
Connection options are found in `couchbase.options`.
PasswordAuthenticator
from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import PasswordAuthenticator
Authentication classes are under `couchbase.auth`.
QueryOptions
from couchbase.options import QueryOptions
Options for N1QL queries are under `couchbase.options`.
acouchbase.cluster.Cluster
from acouchbase.cluster import Cluster, get_event_loop
For `asyncio`-based asynchronous operations, use imports from `acouchbase.cluster`.
txcouchbase
import txcouchbase from twisted.internet import reactor from txcouchbase.cluster import TxCluster
When using `Twisted`, `txcouchbase` *must* be imported before the `twisted.internet.reactor` to ensure the `asyncio` reactor is installed.

This quickstart demonstrates how to connect to a Couchbase cluster, perform basic CRUD (Create, Read, Update, Delete) operations on a document, and handle common exceptions. It uses environment variables for sensitive connection details. Ensure you have a Couchbase cluster running and a bucket available, with appropriate credentials.

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()
Debug
Known issues
breakingMigration 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.
fix
Refer to the 'Migrating to SDK 3 API' documentation for a detailed migration guide.
affects: < 3.0
breakingThe 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.
fix
Thoroughly test existing applications when upgrading from 3.x to 4.x. Avoid relying on internal SDK mechanisms.
affects: All versions 4.0.0 and above, when migrating from 3.x
breakingWhen 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.
fix
Ensure `import txcouchbase` occurs before `from twisted.internet import reactor` in your code.
affects: All versions 4.0.0 and above
gotchaCouchbase 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.
fix
Initialize Couchbase connections within each child process. Consider using `atfork` module if necessary to manage resources during forking.
affects: All versions
gotchaPython 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`.
fix
Upgrade to SDK version 4.1.9 or later. Alternatively, set the `PYCBC_OPENSSL_DIR` environment variable to the path where OpenSSL 1.1 libraries (`libssl-1_1.dll` and `libcrypto-1_1.dll`) can be found.
affects: < 4.1.9 (on Windows with Python 3.11.5+)
deprecatedThe 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).
fix
Always use a currently supported Python version (3.10, 3.11, 3.12, 3.13, 3.14+). Refer to the 'Python Version Compatibility' documentation for the latest supported versions.
affects: All versions (future updates)
gotchaDirect 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.
fix
Rely on the SDK's default connection management for KV operations. Note that `config_poll_interval` for topology changes is configurable and defaults to 2.5 seconds.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'couchbase'
The Couchbase Python SDK or its underlying C library (libcouchbase) is not correctly installed, or the Python interpreter cannot find it due to environment path issues or a conflicting local directory name.
fix
Ensure the SDK is properly installed using `pip install couchbase`. If on Windows, ensure all C++ build tools are available. If a local file or directory is named `couchbase.py` or `couchbase`, rename it to avoid shadowing the installed package.
couchbase.exceptions.DocumentNotFoundException: <Key='your_key', RC=0x12D[LCB_ERR_DOCUMENT_NOT_FOUND (301)], Operational Error, Results=1, C Source=(src/multiresult.c,332), Context={'status_code': 1, 'opaque': 1, 'cas': 0, 'key': 'your_key', ...}>
The application attempted to retrieve or operate on a document using a key that does not exist in the Couchbase bucket or collection.
fix
Implement error handling to catch `DocumentNotFoundException` and gracefully manage scenarios where a document is not found, such as creating a new document or notifying the user. Verify that the key being used for the operation is correct and that the document exists in the specified location.
couchbase.exceptions.AmbiguousTimeoutException
An operation did not receive a response from the Couchbase server within the configured timeout period, and it is uncertain whether the operation completed successfully on the server side.
fix
Increase the operation-specific or global timeout settings if the server is expected to be slow or under heavy load. Investigate network connectivity, monitor server resource utilization, and for N1QL queries, ensure appropriate indexes are created and queries are optimized.
couchbase.exceptions.AuthenticationException: Authentication Failure
The provided username or password for connecting to the Couchbase cluster is incorrect, or the user lacks the necessary permissions for the requested bucket or operations.
fix
Verify the username and password against the Couchbase server's user management settings. Ensure the user has the correct roles and permissions for the target bucket and any specific operations being attempted. Double-check the connection string and cluster address.
RuntimeError: Event loop is closed
This error occurs in asynchronous Python applications, especially on Windows, when an attempt is made to interact with an `asyncio` event loop after it has already been shut down, often due to improper management of asynchronous resources or multiple calls to `asyncio.run()`.
fix
For Windows users, set the `asyncio` event loop policy at the beginning of your application: `import asyncio; import sys; if sys.platform == 'win32': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())`. Ensure all asynchronous resources are properly awaited and closed within the main `asyncio.run()` block or the primary asynchronous context to prevent interaction with a closed event loop during object finalization.
Upgrade
Version history
4.6.3latest on PyPI · released Aug 25, 2026
Audit
Dependencies
pythonrequiredRequires Python 3.7 or later. Python 3.8 support has been dropped in recent SDK versions, and 3.9 will be dropped as it reaches EOL.
C++17 compatible compiler, CMake >= 3.18, GitoptionalRequired for installing from source if no pre-built binary wheel is available for your platform.
OpenSSL 1.1optionalRequired for SDK versions prior to 4.1.9. Versions 4.1.9 and later statically link BoringSSL, removing this direct requirement for binary wheels.
Twisted >= 21.7.0optionalRequired if using the `txcouchbase` API for Twisted-based asynchronous operations.
Agent activity
46 hits · last 30 days
node
40
OpenAI (training)
1
Resources