{"id":1410,"library":"cassandra-driver","title":"DataStax Cassandra Driver","description":"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.","status":"active","version":"3.29.3","language":"en","source_language":"en","source_url":"https://github.com/datastax/python-driver/","tags":["cassandra","database","datastax","nosql","cql"],"install":[{"cmd":"pip install cassandra-driver","lang":"bash","label":"Default Install"}],"dependencies":[],"imports":[{"symbol":"Cluster","correct":"from cassandra.cluster import Cluster"},{"symbol":"PlainTextAuthProvider","correct":"from cassandra.auth import PlainTextAuthProvider"},{"symbol":"ConsistencyLevel","correct":"from cassandra import ConsistencyLevel"},{"symbol":"BatchStatement","correct":"from cassandra.query import BatchStatement"}],"quickstart":{"code":"from cassandra.cluster import Cluster\nfrom cassandra.auth import PlainTextAuthProvider # For secure connections\nimport os\n\n# For local Cassandra, 'contact_points' can be ['127.0.0.1']\n# For Astra DB or secure clusters, specify contact_points and auth_provider\n# using credentials from environment variables.\n# Example: CONTACT_POINTS = ['your.cassandra.host']\n#          ASTRA_CLIENT_ID = os.environ.get('ASTRA_CLIENT_ID', '')\n#          ASTRA_CLIENT_SECRET = os.environ.get('ASTRA_CLIENT_SECRET', '')\n\n# For a basic local connection:\ncluster = Cluster(['127.0.0.1']) # Or specify actual contact points\nsession = None\ntry:\n    session = cluster.connect() # Connects to a default or specified keyspace\n\n    session.execute(\"\"\"\n        CREATE KEYSPACE IF NOT EXISTS my_keyspace WITH replication = {\n            'class': 'SimpleStrategy', 'replication_factor': '1'\n        }\n    \"\"\")\n    session.set_keyspace('my_keyspace')\n\n    session.execute(\"\"\"\n        CREATE TABLE IF NOT EXISTS users (\n            id UUID PRIMARY KEY,\n            name text,\n            age int\n        )\n    \"\"\")\n    print(\"Table 'users' created or already exists.\")\n\n    session.execute(\n        \"INSERT INTO users (id, name, age) VALUES (uuid(), %s, %s)\",\n        (\"John Doe\", 30)\n    )\n    print(\"Data inserted.\")\n\n    rows = session.execute(\"SELECT name, age FROM users WHERE age > 25\")\n    for row in rows:\n        print(f\"User: {row.name}, Age: {row.age}\")\n\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\nfinally:\n    if session:\n        session.shutdown()\n    if cluster:\n        cluster.shutdown()","lang":"python","description":"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."},"warnings":[{"fix":"Consult the official 'Upgrading from Older Drivers' guide in the documentation (e.g., `docs.datastax.com/en/developer/python-driver/3.29/changelog/#upgrading-from-older-drivers`) for detailed migration steps.","message":"Major API changes were introduced between 2.x and 3.x series, affecting `Cluster.connect()` method signatures, result set iteration, and asynchronous APIs. Direct upgrades without code changes will likely fail.","severity":"breaking","affected_versions":"2.x to 3.x"},{"fix":"Always ensure `cluster.shutdown()` and `session.shutdown()` are called in a `finally` block to guarantee resource release. The objects do not support direct `with Cluster(...) as cluster:` context management, requiring explicit shutdown.","message":"Failing to call `.shutdown()` on `Cluster` and `Session` objects can lead to resource leaks (e.g., open connections, threads) and prevent application processes from exiting cleanly, especially in long-running applications or multi-process/multi-threaded contexts.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Instantiate `Cluster` and `Session` objects once per application lifecycle and reuse them. Store them in a global singleton, an application context, or pass them as dependencies.","message":"Creating new `Cluster` or `Session` objects for every database operation is a significant performance anti-pattern. These objects are designed to be long-lived, thread-safe, and shared throughout the application, managing connection pools efficiently.","severity":"gotcha","affected_versions":"All versions"},{"fix":"If schema changes are anticipated, consider clearing the prepared statement cache (`session.clear_cache()`) or re-preparing affected statements explicitly after the schema update. Design your application to handle `InvalidQueryError` for prepared statements gracefully.","message":"Prepared statements are cached by the driver. If the schema of a table (e.g., columns added/removed, types changed) changes after a statement has been prepared, existing prepared statements might become invalid or lead to runtime errors (e.g., `InvalidQueryError`). The driver does not automatically re-prepare statements upon schema changes.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}