or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

async-io.mdauth-policies.mdcluster-session.mdcql-types.mdcqlengine-orm.mdindex.mdmetadata.mdquery-execution.md
tile.json

tessl/pypi-cassandra-driver

Python driver for Apache Cassandra with comprehensive CQL support, connection pooling, and ORM capabilities

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/cassandra-driver@2.7.x

To install, run

npx @tessl/cli install tessl/pypi-cassandra-driver@2.7.0

index.mddocs/

Cassandra Driver

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.

Package Information

  • Package Name: cassandra-driver
  • Language: Python
  • Installation: pip install cassandra-driver
  • Python Versions: 2.6, 2.7, 3.3, 3.4+
  • Protocol Support: Cassandra binary protocol v1-v4

Core Imports

from cassandra.cluster import Cluster, Session
from cassandra.auth import PlainTextAuthProvider
from cassandra import ConsistencyLevel

For query operations:

from cassandra.query import SimpleStatement, PreparedStatement, BatchStatement

For CQLEngine ORM:

from cassandra.cqlengine import connection, management
from cassandra.cqlengine.models import Model
from cassandra.cqlengine.columns import Text, Integer, UUID

Basic Usage

from 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()

Architecture

The cassandra-driver follows a layered architecture designed for performance and flexibility:

Core Components

  • Cluster: Manages connections to multiple Cassandra nodes, handles topology changes, and provides load balancing
  • Session: Executes queries and manages prepared statements within a keyspace context
  • Connection Pool: Maintains pools of connections per host with automatic reconnection
  • Policy Framework: Configurable policies for load balancing, retry logic, and reconnection strategies

Execution Model

  • Synchronous API: Blocking operations returning results immediately
  • Asynchronous API: Non-blocking operations returning ResponseFuture objects
  • Prepared Statements: Server-side query compilation for improved performance
  • Batch Operations: Atomic execution of multiple statements

Type System

  • Native CQL Types: Complete support for all Cassandra data types
  • Collections: Lists, sets, maps with proper encoding/decoding
  • User-Defined Types: Custom composite types with nested structures
  • Time Types: Comprehensive temporal type support including TimeUUID

ORM Integration

  • CQLEngine: Django-inspired ORM with model definitions, query sets, and management operations
  • Schema Management: Automatic table creation and synchronization
  • Validation: Client-side validation with custom validators

Capabilities

Core Connectivity

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): ...

Core Connectivity

Query Execution

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): ...

Query Execution

Authentication & Policies

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): ...

Authentication & Policies

CQL Types & Data

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): ...

CQL Types & Data

Metadata & Schema

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: ...

Metadata & Schema

CQLEngine ORM

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): ...

CQLEngine ORM

Asynchronous I/O

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): ...

Asynchronous I/O

Exception Handling

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 Information

__version__: str
__version_info__: tuple

Constants

class 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