CouchDB Python Library

1.2 · abandoned · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a CouchDB server, create or access a database, save a document with a client-side ID, retrieve, update, and finally delete a document and the database. It includes basic error handling for common issues and uses environment variables for credentials, which is crucial for CouchDB 3.x and above.

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}")

view raw JSON →