{"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":"python","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"},{"fix":"Ensure that the Apache Cassandra database server (or DataStax Astra DB) is running and accessible from the client machine on the specified host and port. Verify network connectivity, firewall rules, and the `listen_address`/`rpc_address` configuration in `cassandra.yaml` if running a local Cassandra instance.","message":"The Python driver requires a running Apache Cassandra or DataStax Astra DB instance to connect. A `ConnectionRefusedError` indicates the driver was unable to establish a connection to the specified host and port (typically 127.0.0.1:9042), suggesting the database server is not running, is unreachable, or configured incorrectly.","severity":"breaking","affected_versions":"All versions"},{"fix":"Use a `cassandra-driver` version that explicitly supports Python 3.13+ (check the official documentation for compatibility). Alternatively, install the driver on an older, compatible Python version (e.g., Python 3.12 or earlier) if upgrading the driver is not feasible.","message":"Installation of older `cassandra-driver` versions on Python 3.13+ fails due to outdated build scripts (e.g., `ez_setup.py`) which rely on `pkg_resources` and `tarfile.chown()` signatures that have changed or been removed in recent Python versions. This prevents the package from being built or installed.","severity":"breaking","affected_versions":"Older versions of `cassandra-driver` (likely 3.28.0 and below) when installed on Python 3.13 and later."}],"env_vars":null,"search_vec":"'3.29.3':58 'align':62 'allow':18 'apach':9 'api':37 'applic':20 'astra':30 'asynchron':41 'cassandra':2,10,27,49,66,73 'client':14 'client-sid':13 'cluster':32 'connect':22 'cql':52,77 'current':54 'databas':74 'datastax':1,5,29,75 'db':31 'driver':3,7 'featur':68 'general':61 'integr':46 'interact':25 'languag':51 'librari':16 'major':71 'nosql':76 'oper':42 'prepar':43 'provid':34 'python':6,19 'queri':50 'releas':64 'rich':36 'set':69 'side':15 'stabl':55 'statement':44 'synchron':39 'version':56,72","created_at":"2026-04-09T03:46:44.116662+00:00","updated_at":"2026-04-16T01:30:47.247427+00:00","problems":[{"fix":"Ensure the DataStax Python Driver for Apache Cassandra is installed using pip: `pip install cassandra-driver`.","cause":"The cassandra-driver Python package is not installed or not accessible in the current Python environment. This often happens if the package was never installed, or if there's a Python environment mismatch.","error":"ModuleNotFoundError: No module named 'cassandra.cluster'"},{"fix":"Verify that your Cassandra cluster nodes are running (`nodetool status`), check the accuracy of contact point IP addresses and the CQL port (default 9042), and ensure no network or firewall rules are blocking communication. Consider configuring a `ReconnectionPolicy` in your `Cluster` configuration to handle transient outages.","cause":"The driver failed to connect to any of the specified Cassandra contact points. This can occur if Cassandra nodes are down, IP addresses or ports are incorrect, or network/firewall issues prevent connection.","error":"NoHostAvailable"},{"fix":"Double-check the username and password used for the connection. Confirm that `authenticator: PasswordAuthenticator` (or the appropriate authenticator for your setup) is correctly configured in `cassandra.yaml` on all Cassandra nodes and that the nodes have been restarted after changes.","cause":"The driver failed to authenticate with the Cassandra cluster. This usually means the provided username or password is incorrect, or the Cassandra cluster's authentication settings (e.g., `authenticator` in `cassandra.yaml`) are misconfigured.","error":"AuthenticationFailed"},{"fix":"Increase the `read_timeout_millis` setting in your Cluster configuration to allow more time for responses. Investigate Cassandra node performance (CPU, memory, disk I/O), network latency between nodes, and optimize your data model to avoid excessively large partitions or rows, which can contribute to slow reads.","cause":"A read query did not receive enough responses from the Cassandra replicas within the configured timeout period. This can be caused by high network latency, overloaded Cassandra nodes, large data partitions requiring more time to read, or a client-side timeout that is too short.","error":"ReadTimeoutException"}],"ecosystem":"pypi","meta_description":null,"install_score":77,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"3.30.1","cli_name":"","cli_version":null,"type":"library","homepage":"https://docs.datastax.com/en/developer/python-driver/latest","github":"https://github.com/apache/cassandra-python-driver","docs":"https://docs.datastax.com/en/developer/python-driver/latest/","changelog":"https://github.com/apache/cassandra-python-driver/blob/trunk/CHANGELOG.rst","pypi":"https://pypi.org/project/cassandra-driver/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["database","http-networking"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-27","next_check":"2026-07-28","install_tag":"reviewed"}}