0
# Cloudant Python Client Library
1
2
IBM Cloudant Python client library providing comprehensive interface for Cloudant and CouchDB databases. This library offers high-level abstractions for database operations including document management, indexing, querying, replication, and change feed monitoring with robust session management and authentication support.
3
4
**Note**: This library has been deprecated as of December 31, 2021. Users are encouraged to migrate to the newer `cloudant-python-sdk` for continued support.
5
6
## Package Information
7
8
- **Package Name**: cloudant
9
- **Language**: Python
10
- **Version**: 2.15.0
11
- **Installation**: `pip install cloudant`
12
- **License**: Apache-2.0
13
14
## Core Imports
15
16
```python
17
from cloudant import cloudant, cloudant_iam, couchdb
18
from cloudant.client import Cloudant, CouchDB
19
from cloudant.database import CloudantDatabase, CouchDatabase
20
from cloudant.document import Document
21
from cloudant.security_document import SecurityDocument
22
from cloudant.scheduler import Scheduler
23
from cloudant.adapters import Replay429Adapter
24
from cloudant.result import Result, QueryResult, ResultByKey
25
from cloudant.error import CloudantException
26
```
27
28
## Basic Usage
29
30
### Context Manager Pattern (Recommended)
31
32
```python
33
from cloudant import cloudant
34
35
# Basic authentication
36
with cloudant(username, password, account=account_name) as client:
37
# Access databases
38
db = client['my_database']
39
40
# Work with documents
41
doc = db['my_document']
42
doc['field'] = 'value'
43
doc.save()
44
45
# Query documents
46
for document in db:
47
print(document['_id'])
48
49
# IAM authentication
50
from cloudant import cloudant_iam
51
52
with cloudant_iam(account_name, api_key) as client:
53
db = client['my_database']
54
# ... work with database
55
```
56
57
### Direct Client Usage
58
59
```python
60
from cloudant.client import Cloudant
61
62
client = Cloudant(username, password, account=account_name)
63
client.connect()
64
65
try:
66
# Create database
67
db = client.create_database('my_database')
68
69
# Create document
70
doc = db.create_document({'name': 'John', 'age': 30})
71
72
# Query documents
73
result = db.all_docs(include_docs=True)
74
for row in result:
75
print(row['doc'])
76
77
finally:
78
client.disconnect()
79
```
80
81
## Architecture
82
83
The library follows a hierarchical object model:
84
85
- **Client**: Top-level connection to Cloudant/CouchDB server with authentication and session management
86
- **Database**: Represents individual databases with document and view operations
87
- **Document**: Individual JSON documents with CRUD operations and conflict resolution
88
- **DesignDocument**: Special documents containing views, indexes, and other database functions
89
- **Result**: Iterator collections for query results with pagination and key-based access
90
- **Feed**: Streaming iterators for change feeds and database updates
91
92
## Capabilities
93
94
### Client Connection and Authentication
95
96
Establish connections to Cloudant and CouchDB servers with support for multiple authentication methods including basic auth, IAM, and Cloud Foundry integration.
97
98
```python { .api }
99
def cloudant(user, passwd, **kwargs): ...
100
def cloudant_iam(account_name, api_key, **kwargs): ...
101
def cloudant_bluemix(vcap_services, instance_name=None, service_name=None, **kwargs): ...
102
def couchdb(user, passwd, **kwargs): ...
103
104
class Cloudant(CouchDB):
105
def __init__(self, user, auth_token, admin_party=False, **kwargs): ...
106
@classmethod
107
def iam(cls, account_name, api_key, **kwargs): ...
108
@classmethod
109
def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs): ...
110
```
111
112
[Client Connection and Authentication](./authentication.md)
113
114
### Database Management
115
116
Create, delete, and manage databases with support for both CouchDB and Cloudant-specific features including partitioned databases and shard information.
117
118
```python { .api }
119
class CouchDatabase(dict):
120
def __init__(self, client, database_name, fetch_limit=100, partitioned=False): ...
121
def create(self, throw_on_exists=False): ...
122
def delete(self): ...
123
def exists(self): ...
124
def metadata(self): ...
125
def doc_count(self): ...
126
127
class CloudantDatabase(CouchDatabase):
128
def shards(self): ...
129
def share_database(self, username, roles=None): ...
130
def unshare_database(self, username): ...
131
```
132
133
[Database Management](./database-management.md)
134
135
### Document Operations
136
137
Complete CRUD operations for JSON documents with attachment support, conflict resolution, and batch operations.
138
139
```python { .api }
140
class Document(dict):
141
def __init__(self, database, document_id=None, **kwargs): ...
142
def create(self): ...
143
def fetch(self): ...
144
def save(self): ...
145
def delete(self): ...
146
def update_field(self, action, field, value, max_tries=10): ...
147
def get_attachment(self, attachment, headers=None, write_to=None, attachment_type=None): ...
148
def put_attachment(self, attachment, content_type, data, headers=None): ...
149
```
150
151
[Document Operations](./document-operations.md)
152
153
### Query and Indexing
154
155
Query documents using Cloudant Query (Mango) with JSON indexes, text search, and pagination support.
156
157
```python { .api }
158
class Query:
159
def __init__(self, database, selector=None, fields=None, **kwargs): ...
160
def __call__(self, **kwargs): ...
161
162
class Index:
163
def __init__(self, database, design_document_id=None, name=None, partitioned=None, **kwargs): ...
164
def create(self): ...
165
def delete(self): ...
166
167
class TextIndex(Index): ...
168
```
169
170
[Query and Indexing](./query-indexing.md)
171
172
### Views and Design Documents
173
174
Manage MapReduce views, list functions, show functions, and update handlers through design documents.
175
176
```python { .api }
177
class DesignDocument(Document):
178
def __init__(self, database, document_id=None, partitioned=False): ...
179
180
class View:
181
def __init__(self, design_document, view_name, **kwargs): ...
182
def __call__(self, **kwargs): ...
183
```
184
185
[Views and Design Documents](./views-design-documents.md)
186
187
### Replication
188
189
Set up and manage database replication between Cloudant instances with progress monitoring and state management.
190
191
```python { .api }
192
class Replicator:
193
def __init__(self, client): ...
194
def create_replication(self, source_db=None, target_db=None, repl_id=None, **kwargs): ...
195
def list_replications(self): ...
196
def replication_state(self, repl_id): ...
197
def stop_replication(self, repl_id): ...
198
def follow_replication(self, repl_id): ...
199
```
200
201
[Replication](./replication.md)
202
203
### Change Feeds and Monitoring
204
205
Monitor database changes in real-time with support for continuous feeds, filtering, and infinite monitoring.
206
207
```python { .api }
208
class Feed:
209
def __init__(self, source, raw_data=False, **options): ...
210
def stop(self): ...
211
def __iter__(self): ...
212
213
class InfiniteFeed(Feed): ...
214
```
215
216
[Change Feeds and Monitoring](./change-feeds.md)
217
218
### Error Handling
219
220
Comprehensive exception hierarchy for handling different types of errors with specific exceptions for client, database, document, and operation-specific failures.
221
222
```python { .api }
223
class CloudantException(Exception): ...
224
class CloudantClientException(CloudantException): ...
225
class CloudantDatabaseException(CloudantException): ...
226
class CloudantDocumentException(CloudantException): ...
227
class CloudantArgumentError(CloudantException): ...
228
```
229
230
[Error Handling](./error-handling.md)
231
232
### Security Document Management
233
234
Manage database access permissions and user roles through security documents with context manager support for automatic fetch and save operations.
235
236
```python { .api }
237
class SecurityDocument(dict):
238
def __init__(self, database): ...
239
def fetch(self): ...
240
def save(self): ...
241
def json(self): ...
242
def __enter__(self): ...
243
def __exit__(self, *args): ...
244
```
245
246
[Security Document Management](./security-document.md)
247
248
### Scheduler Monitoring
249
250
Monitor and query replication jobs and documents using the scheduler API for visibility into active, completed, and failed replications.
251
252
```python { .api }
253
class Scheduler:
254
def __init__(self, client): ...
255
def list_docs(self, limit=None, skip=None): ...
256
def get_doc(self, doc_id): ...
257
def list_jobs(self, limit=None, skip=None): ...
258
```
259
260
[Scheduler Monitoring](./scheduler-monitoring.md)
261
262
### HTTP Adapters
263
264
Custom HTTP transport adapters for handling rate limiting, retries, and connection management with automatic 429 response handling.
265
266
```python { .api }
267
class Replay429Adapter(HTTPAdapter):
268
def __init__(self, retries=3, initialBackoff=0.25): ...
269
```
270
271
[HTTP Adapters](./http-adapters.md)
272
273
## Common Types
274
275
```python { .api }
276
# Authentication credentials
277
CloudFoundryService:
278
username: str
279
password: str
280
url: str
281
iam_api_key: str
282
283
# Result collections
284
class Result:
285
def __getitem__(self, key): ...
286
def __iter__(self): ...
287
def __len__(self): ...
288
def all(self): ...
289
290
class QueryResult(Result): ...
291
292
class ResultByKey:
293
def __init__(self, value): ...
294
def __call__(self): ...
295
296
# Security document structure
297
SecurityDocumentData = dict[str, Any]
298
CloudantSection = dict[str, list[str]] # username -> roles
299
CouchDBSection = dict[str, list[str]] # keys: "names", "roles"
300
301
# Scheduler responses
302
DocsResponse = dict[str, Any] # Contains total_rows, offset, docs
303
JobsResponse = dict[str, Any] # Contains total_rows, offset, jobs
304
ReplicationDoc = dict[str, Any]
305
ReplicationJob = dict[str, Any]
306
307
# Feed options
308
FeedOptions = dict[str, Any] # feed parameters like heartbeat, timeout, since
309
310
# Index types
311
JSON_INDEX_TYPE = "json"
312
TEXT_INDEX_TYPE = "text"
313
SPECIAL_INDEX_TYPE = "special"
314
315
# HTTP adapter configuration
316
AdapterConfig = dict[str, Any]
317
RetryConfig = dict[str, Any]
318
```