Python driver for Apache Cassandra with comprehensive CQL support, connection pooling, and ORM capabilities
npx @tessl/cli install tessl/pypi-cassandra-driver@2.7.0A 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.
pip install cassandra-driverfrom cassandra.cluster import Cluster, Session
from cassandra.auth import PlainTextAuthProvider
from cassandra import ConsistencyLevelFor query operations:
from cassandra.query import SimpleStatement, PreparedStatement, BatchStatementFor CQLEngine ORM:
from cassandra.cqlengine import connection, management
from cassandra.cqlengine.models import Model
from cassandra.cqlengine.columns import Text, Integer, UUIDfrom cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
# Create cluster connection
auth_provider = PlainTextAuthProvider(username='user', password='pass')
cluster = Cluster(['127.0.0.1'], auth_provider=auth_provider)
session = cluster.connect()
# Create keyspace and table
session.execute("""
CREATE KEYSPACE IF NOT EXISTS demo
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}
""")
session.set_keyspace('demo')
session.execute("""
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
name TEXT,
age INT
)
""")
# Insert data
import uuid
session.execute(
"INSERT INTO users (id, name, age) VALUES (%s, %s, %s)",
(uuid.uuid4(), 'Alice', 30)
)
# Query data
rows = session.execute("SELECT * FROM users")
for row in rows:
print(f"User: {row.name}, Age: {row.age}")
# Clean up
cluster.shutdown()The cassandra-driver follows a layered architecture designed for performance and flexibility:
Primary cluster connection management, session handling, and connection pooling functionality.
class Cluster:
def __init__(self, contact_points=None, port=9042, **kwargs): ...
def connect(self, keyspace=None): ...
def shutdown(self): ...
class Session:
def execute(self, query, parameters=None, **kwargs): ...
def execute_async(self, query, parameters=None, **kwargs): ...
def prepare(self, query): ...
def shutdown(self): ...Statement types, query execution, batch operations, and result handling with comprehensive parameter binding and tracing support.
class SimpleStatement:
def __init__(self, query_string, **kwargs): ...
class PreparedStatement:
def bind(self, values): ...
class BatchStatement:
def add(self, statement, parameters=None): ...
def add_all(self, statements_and_parameters): ...Authentication providers, load balancing policies, retry strategies, and reconnection policies for robust cluster operations.
class PlainTextAuthProvider:
def __init__(self, username, password): ...
class RoundRobinPolicy:
def __init__(self): ...
class TokenAwarePolicy:
def __init__(self, child_policy): ...
class ExponentialReconnectionPolicy:
def __init__(self, base_delay, max_delay): ...Comprehensive type system with encoding/decoding support for all Cassandra data types, collections, and user-defined types.
class UUIDType: ...
class UTF8Type: ...
class Int32Type: ...
class ListType: ...
class MapType: ...
class UserType: ...
def lookup_casstype(casstype_name): ...
def datetime_from_timestamp(timestamp): ...
def uuid_from_time(time_arg): ...Cluster metadata access, schema introspection, and topology information with complete keyspace, table, and column metadata.
class Metadata:
def get_keyspace(self, keyspace): ...
def get_table(self, keyspace, table): ...
def get_user_type(self, keyspace, user_type): ...
class KeyspaceMetadata: ...
class TableMetadata: ...
class ColumnMetadata: ...Object-relational mapping system with Django-inspired model definitions, query operations, and schema management.
def setup(hosts, keyspace, **kwargs): ...
class Model:
def save(self): ...
def delete(self): ...
@classmethod
def objects(cls): ...
class Column: ...
class Text(Column): ...
class Integer(Column): ...
class UUID(Column): ...
def sync_table(model): ...
def create_keyspace_simple(keyspace_name, replication_factor): ...I/O reactor implementations, concurrent execution utilities, and asynchronous operation patterns for high-performance applications.
class ResponseFuture:
def result(self): ...
def add_callback(self, fn, *args, **kwargs): ...
def add_errback(self, fn, *args, **kwargs): ...
def execute_concurrent(session, statements_and_parameters, **kwargs): ...
def execute_concurrent_with_args(session, statement, parameters, **kwargs): ...The driver provides comprehensive exception handling for various failure scenarios:
class Unavailable(Exception):
consistency: int
required_replicas: int
alive_replicas: int
class ReadTimeout(Exception):
consistency: int
required_responses: int
received_responses: int
data_retrieved: bool
class WriteTimeout(Exception):
consistency: int
required_responses: int
received_responses: int
write_type: str
class NoHostAvailable(Exception):
errors: dict
class OperationTimedOut(Exception):
errors: dict
last_host: str__version__: str
__version_info__: tupleclass ConsistencyLevel:
ANY: int
ONE: int
TWO: int
THREE: int
QUORUM: int
ALL: int
LOCAL_QUORUM: int
EACH_QUORUM: int
SERIAL: int
LOCAL_SERIAL: int
LOCAL_ONE: int