DataStax Cassandra Driver

3.29.3 · active · verified Thu Apr 09

The DataStax Python Driver for Apache Cassandra is a client-side library that allows Python applications to connect to and interact with Cassandra and DataStax Astra DB clusters. It provides a rich API for synchronous and asynchronous operations, prepared statements, and integrates with the Cassandra Query Language (CQL). The current stable version is 3.29.3, and it generally aligns its releases with Cassandra's feature set and major versions.

Warnings

Install

Imports

Quickstart

This quickstart connects to a local Cassandra instance (at 127.0.0.1), creates a keyspace and table if they don't exist, inserts a row, and then queries data. For production environments or Astra DB, `contact_points` should be set to your cluster's actual endpoints, and `PlainTextAuthProvider` should be used with credentials (e.g., from environment variables) for secure connections. Ensure `Cluster` and `Session` objects are properly shut down to release resources.

from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider # For secure connections
import os

# For local Cassandra, 'contact_points' can be ['127.0.0.1']
# For Astra DB or secure clusters, specify contact_points and auth_provider
# using credentials from environment variables.
# Example: CONTACT_POINTS = ['your.cassandra.host']
#          ASTRA_CLIENT_ID = os.environ.get('ASTRA_CLIENT_ID', '')
#          ASTRA_CLIENT_SECRET = os.environ.get('ASTRA_CLIENT_SECRET', '')

# For a basic local connection:
cluster = Cluster(['127.0.0.1']) # Or specify actual contact points
session = None
try:
    session = cluster.connect() # Connects to a default or specified keyspace

    session.execute("""
        CREATE KEYSPACE IF NOT EXISTS my_keyspace WITH replication = {
            'class': 'SimpleStrategy', 'replication_factor': '1'
        }
    """)
    session.set_keyspace('my_keyspace')

    session.execute("""
        CREATE TABLE IF NOT EXISTS users (
            id UUID PRIMARY KEY,
            name text,
            age int
        )
    """)
    print("Table 'users' created or already exists.")

    session.execute(
        "INSERT INTO users (id, name, age) VALUES (uuid(), %s, %s)",
        ("John Doe", 30)
    )
    print("Data inserted.")

    rows = session.execute("SELECT name, age FROM users WHERE age > 25")
    for row in rows:
        print(f"User: {row.name}, Age: {row.age}")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    if session:
        session.shutdown()
    if cluster:
        cluster.shutdown()

view raw JSON →