CouchDB Python Library
The `couchdb` Python package provides a client library for working with Apache CouchDB. It offers modules for interfacing with CouchDB servers, managing design documents, mapping JSON documents to Python objects, and a Python-based view server. While version 1.2 was released in 2018, the library is officially no longer being maintained, and users are encouraged to consider `python-cloudant` as an alternative.
Common errors
-
couchdb.http.InvalidURL: Nonnumeric port
cause This error typically occurs when the connection URL contains special characters (like ':' or '@') in the username or password fields that are not properly URL-encoded, or when the credentials are inserted in a way that the URL parser misinterprets parts of them as a port number.fixEnsure username and password parts of the URL are percent-encoded if they contain special characters. Alternatively, pass credentials separately if the client library supports it, or reconstruct the URL carefully. Example: `server = couchdb.Server(f'http://{requests.utils.quote(user)}:{requests.utils.quote(password)}@{host}:{port}/')`. -
AttributeError: module 'http' has no attribute 'client'
cause This error (or similar ones related to `json` modules) can arise in earlier Python 3.x versions (before 3.4, which is officially unsupported by `couchdb` 1.2) due to naming conflicts between the `couchdb.http` and `couchdb.json` internal modules and Python's built-in `http` and `json` standard library modules.fixUpgrade to Python 3.4 or higher, which `couchdb` 1.2 officially supports and where many of these compatibility issues were addressed. If upgrading is not an option, consider using `python-cloudant`. -
couchdb.http.ResourceNotFound: ('not_found', 'missing')cause The specified database or document ID does not exist on the CouchDB server. This can happen if you try to access a database that hasn't been created or a document with an incorrect ID.fixVerify that the database name is correct and that it exists (`db_name in server`). For documents, double-check the `_id` you are using. If creating a new database, ensure `server.create(db_name)` is called.
Warnings
- breaking The `couchdb` Python library is no longer being actively maintained. Users are strongly encouraged to migrate to `python-cloudant` (IBM Cloudant's official library, compatible with Apache CouchDB) for continued support and new features.
- gotcha Avoid using `db.create()` for documents where an `_id` is not specified, allowing CouchDB to generate IDs. The underlying HTTP POST operation is not idempotent, and retries due to network issues can lead to duplicate documents being created. Always specify `_id` on the client side when saving documents.
- breaking Version 1.2 of `couchdb` removed support for Python 2.6 and Python 3.x versions older than 3.4. Attempting to use it with unsupported Python versions may lead to unexpected errors or installation failures.
- gotcha When connecting to CouchDB version 3 or higher, it is mandatory to specify user credentials (username and password) in the connection URL to avoid `couchdb.http.Unauthorized` errors. The default `http://localhost:5984/` without credentials will not work.
- gotcha Document update conflicts (`couchdb.http.ResourceConflict` or `CouchDBDocumentConflict` if using `couchdb.mapping`) occur if you attempt to save a document without its latest `_rev` field. This happens when another process updates the document between your retrieval and save operations.
Install
-
pip install couchdb
Imports
- Server
import couchdb server = couchdb.Server('http://user:pass@host:port/') - Database
from couchdb.client import Database
db = server['mydb_name']
Quickstart
import couchdb
import os
# Configure connection details, including authentication for CouchDB 3.x+
# Use environment variables for sensitive data in production
COUCHDB_URL = os.environ.get('COUCHDB_URL', 'http://localhost:5984/')
COUCHDB_USER = os.environ.get('COUCHDB_USER', 'admin')
COUCHDB_PASSWORD = os.environ.get('COUCHDB_PASSWORD', 'password')
# Construct the URL with credentials for CouchDB 3.x and above
# Note: ensure username/password are URL-encoded if they contain special characters
if COUCHDB_USER and COUCHDB_PASSWORD:
auth_url = f'http://{COUCHDB_USER}:{COUCHDB_PASSWORD}@{COUCHDB_URL.split('//')[-1]}'
else:
auth_url = COUCHDB_URL
try:
server = couchdb.Server(auth_url)
# Check if a database exists, create if not
db_name = 'my_test_database'
if db_name not in server:
db = server.create(db_name)
print(f"Database '{db_name}' created.")
else:
db = server[db_name]
print(f"Connected to existing database '{db_name}'.")
# Create and save a document
doc = {'_id': 'mydoc1', 'name': 'John Doe', 'age': 30}
db.save(doc)
print(f"Document saved: {doc['_id']} (rev: {doc['_rev']})")
# Retrieve a document
retrieved_doc = db['mydoc1']
print(f"Retrieved document: {retrieved_doc}")
# Update a document (must have the latest revision)
retrieved_doc['age'] = 31
db.save(retrieved_doc)
print(f"Document updated: {retrieved_doc['_id']} (new rev: {retrieved_doc['_rev']})")
# Delete the document
db.delete(retrieved_doc)
print(f"Document '{retrieved_doc['_id']}' deleted.")
# Delete the database (optional)
del server[db_name]
print(f"Database '{db_name}' deleted.")
except couchdb.http.ResourceNotFound as e:
print(f"Error: Resource not found. Check database name or document ID. Details: {e}")
except couchdb.http.Unauthorized as e:
print(f"Error: Authentication failed. Check COUCHDB_USER and COUCHDB_PASSWORD. Details: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")