Python driver for Apache Cassandra with comprehensive CQL support, connection pooling, and ORM capabilities
npx @tessl/cli install tessl/pypi-cassandra-driver@2.7.00
# Cassandra Driver
1
2
A modern, feature-rich Python client library for Apache Cassandra and DataStax Enterprise. Provides both synchronous and asynchronous APIs with comprehensive support for CQL operations, connection pooling, load balancing, and an integrated object-relational mapping system.
3
4
## Package Information
5
6
- **Package Name**: cassandra-driver
7
- **Language**: Python
8
- **Installation**: `pip install cassandra-driver`
9
- **Python Versions**: 2.6, 2.7, 3.3, 3.4+
10
- **Protocol Support**: Cassandra binary protocol v1-v4
11
12
## Core Imports
13
14
```python
15
from cassandra.cluster import Cluster, Session
16
from cassandra.auth import PlainTextAuthProvider
17
from cassandra import ConsistencyLevel
18
```
19
20
For query operations:
21
22
```python
23
from cassandra.query import SimpleStatement, PreparedStatement, BatchStatement
24
```
25
26
For CQLEngine ORM:
27
28
```python
29
from cassandra.cqlengine import connection, management
30
from cassandra.cqlengine.models import Model
31
from cassandra.cqlengine.columns import Text, Integer, UUID
32
```
33
34
## Basic Usage
35
36
```python
37
from cassandra.cluster import Cluster
38
from cassandra.auth import PlainTextAuthProvider
39
40
# Create cluster connection
41
auth_provider = PlainTextAuthProvider(username='user', password='pass')
42
cluster = Cluster(['127.0.0.1'], auth_provider=auth_provider)
43
session = cluster.connect()
44
45
# Create keyspace and table
46
session.execute("""
47
CREATE KEYSPACE IF NOT EXISTS demo
48
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}
49
""")
50
session.set_keyspace('demo')
51
52
session.execute("""
53
CREATE TABLE IF NOT EXISTS users (
54
id UUID PRIMARY KEY,
55
name TEXT,
56
age INT
57
)
58
""")
59
60
# Insert data
61
import uuid
62
session.execute(
63
"INSERT INTO users (id, name, age) VALUES (%s, %s, %s)",
64
(uuid.uuid4(), 'Alice', 30)
65
)
66
67
# Query data
68
rows = session.execute("SELECT * FROM users")
69
for row in rows:
70
print(f"User: {row.name}, Age: {row.age}")
71
72
# Clean up
73
cluster.shutdown()
74
```
75
76
## Architecture
77
78
The cassandra-driver follows a layered architecture designed for performance and flexibility:
79
80
### Core Components
81
82
- **Cluster**: Manages connections to multiple Cassandra nodes, handles topology changes, and provides load balancing
83
- **Session**: Executes queries and manages prepared statements within a keyspace context
84
- **Connection Pool**: Maintains pools of connections per host with automatic reconnection
85
- **Policy Framework**: Configurable policies for load balancing, retry logic, and reconnection strategies
86
87
### Execution Model
88
89
- **Synchronous API**: Blocking operations returning results immediately
90
- **Asynchronous API**: Non-blocking operations returning ResponseFuture objects
91
- **Prepared Statements**: Server-side query compilation for improved performance
92
- **Batch Operations**: Atomic execution of multiple statements
93
94
### Type System
95
96
- **Native CQL Types**: Complete support for all Cassandra data types
97
- **Collections**: Lists, sets, maps with proper encoding/decoding
98
- **User-Defined Types**: Custom composite types with nested structures
99
- **Time Types**: Comprehensive temporal type support including TimeUUID
100
101
### ORM Integration
102
103
- **CQLEngine**: Django-inspired ORM with model definitions, query sets, and management operations
104
- **Schema Management**: Automatic table creation and synchronization
105
- **Validation**: Client-side validation with custom validators
106
107
## Capabilities
108
109
### Core Connectivity
110
111
Primary cluster connection management, session handling, and connection pooling functionality.
112
113
```python { .api }
114
class Cluster:
115
def __init__(self, contact_points=None, port=9042, **kwargs): ...
116
def connect(self, keyspace=None): ...
117
def shutdown(self): ...
118
119
class Session:
120
def execute(self, query, parameters=None, **kwargs): ...
121
def execute_async(self, query, parameters=None, **kwargs): ...
122
def prepare(self, query): ...
123
def shutdown(self): ...
124
```
125
126
[Core Connectivity](./cluster-session.md)
127
128
### Query Execution
129
130
Statement types, query execution, batch operations, and result handling with comprehensive parameter binding and tracing support.
131
132
```python { .api }
133
class SimpleStatement:
134
def __init__(self, query_string, **kwargs): ...
135
136
class PreparedStatement:
137
def bind(self, values): ...
138
139
class BatchStatement:
140
def add(self, statement, parameters=None): ...
141
def add_all(self, statements_and_parameters): ...
142
```
143
144
[Query Execution](./query-execution.md)
145
146
### Authentication & Policies
147
148
Authentication providers, load balancing policies, retry strategies, and reconnection policies for robust cluster operations.
149
150
```python { .api }
151
class PlainTextAuthProvider:
152
def __init__(self, username, password): ...
153
154
class RoundRobinPolicy:
155
def __init__(self): ...
156
157
class TokenAwarePolicy:
158
def __init__(self, child_policy): ...
159
160
class ExponentialReconnectionPolicy:
161
def __init__(self, base_delay, max_delay): ...
162
```
163
164
[Authentication & Policies](./auth-policies.md)
165
166
### CQL Types & Data
167
168
Comprehensive type system with encoding/decoding support for all Cassandra data types, collections, and user-defined types.
169
170
```python { .api }
171
class UUIDType: ...
172
class UTF8Type: ...
173
class Int32Type: ...
174
class ListType: ...
175
class MapType: ...
176
class UserType: ...
177
178
def lookup_casstype(casstype_name): ...
179
def datetime_from_timestamp(timestamp): ...
180
def uuid_from_time(time_arg): ...
181
```
182
183
[CQL Types & Data](./cql-types.md)
184
185
### Metadata & Schema
186
187
Cluster metadata access, schema introspection, and topology information with complete keyspace, table, and column metadata.
188
189
```python { .api }
190
class Metadata:
191
def get_keyspace(self, keyspace): ...
192
def get_table(self, keyspace, table): ...
193
def get_user_type(self, keyspace, user_type): ...
194
195
class KeyspaceMetadata: ...
196
class TableMetadata: ...
197
class ColumnMetadata: ...
198
```
199
200
[Metadata & Schema](./metadata.md)
201
202
### CQLEngine ORM
203
204
Object-relational mapping system with Django-inspired model definitions, query operations, and schema management.
205
206
```python { .api }
207
def setup(hosts, keyspace, **kwargs): ...
208
209
class Model:
210
def save(self): ...
211
def delete(self): ...
212
@classmethod
213
def objects(cls): ...
214
215
class Column: ...
216
class Text(Column): ...
217
class Integer(Column): ...
218
class UUID(Column): ...
219
220
def sync_table(model): ...
221
def create_keyspace_simple(keyspace_name, replication_factor): ...
222
```
223
224
[CQLEngine ORM](./cqlengine-orm.md)
225
226
### Asynchronous I/O
227
228
I/O reactor implementations, concurrent execution utilities, and asynchronous operation patterns for high-performance applications.
229
230
```python { .api }
231
class ResponseFuture:
232
def result(self): ...
233
def add_callback(self, fn, *args, **kwargs): ...
234
def add_errback(self, fn, *args, **kwargs): ...
235
236
def execute_concurrent(session, statements_and_parameters, **kwargs): ...
237
def execute_concurrent_with_args(session, statement, parameters, **kwargs): ...
238
```
239
240
[Asynchronous I/O](./async-io.md)
241
242
## Exception Handling
243
244
The driver provides comprehensive exception handling for various failure scenarios:
245
246
```python { .api }
247
class Unavailable(Exception):
248
consistency: int
249
required_replicas: int
250
alive_replicas: int
251
252
class ReadTimeout(Exception):
253
consistency: int
254
required_responses: int
255
received_responses: int
256
data_retrieved: bool
257
258
class WriteTimeout(Exception):
259
consistency: int
260
required_responses: int
261
received_responses: int
262
write_type: str
263
264
class NoHostAvailable(Exception):
265
errors: dict
266
267
class OperationTimedOut(Exception):
268
errors: dict
269
last_host: str
270
```
271
272
## Version Information
273
274
```python { .api }
275
__version__: str
276
__version_info__: tuple
277
```
278
279
## Constants
280
281
```python { .api }
282
class ConsistencyLevel:
283
ANY: int
284
ONE: int
285
TWO: int
286
THREE: int
287
QUORUM: int
288
ALL: int
289
LOCAL_QUORUM: int
290
EACH_QUORUM: int
291
SERIAL: int
292
LOCAL_SERIAL: int
293
LOCAL_ONE: int
294
```