DataStax Python driver

Use the unified DataStax Python driver to connect to your DataStax Astra DB database and begin building your own application.

DataStax recommends using the unified DataStax Python driver. If you have an existing Apache Cassandra or DataStax Enterprise (DSE) Python driver, migrate the driver to a version that is capable of connecting to Astra DB databases.

Prerequisites

Procedure

  1. Install the DataStax Python driver.

    pip install cassandra-driver

    See the Python driver installation instructions for more information.

  2. Verify that the DataStax Python driver installed successfully:

    python -c 'import cassandra;
    print (cassandra.*version*)'

    The version number displays in the console output: 3.23.0

  3. Create a connect_database.py file in the main directory for your Python project.

    cd python_project
    touch connect_database.py
  4. Copy the following connection code into the connect_database.py file.

    Set the cloud_config parameter for the Cluster initialization as shown in the following example. The secure_connect_bundle must include the absolute path to your Astra DB database credentials (secure-connect-database_name.zip).

    from cassandra.cluster import Cluster
    from cassandra.auth import PlainTextAuthProvider
    
    cloud_config= {
            'secure_connect_bundle': '/path/to/secure-connect-database_name.zip'
    }
    auth_provider = PlainTextAuthProvider('username', 'password')
    cluster = Cluster(cloud=cloud_config, auth_provider=auth_provider)
    session = cluster.connect()
  5. After the connection code, add the following code to connect-database.py. This code creates a Cluster instance to connect to your Astra DB database, runs a CQL query, and prints the output to the console. As the name suggests, you will typically have one instance of Cluster for each Cassandra cluster you want to interact with.

    row = session.execute("select release_version from system.local").one()
    if row:
        print(row[0])
        else:
            print("An error occurred.")
  6. Save and close the connect_database.py file.

  7. Run connect_database.py.

    python ./connect_database.py

    The console output displays the release_version from the system.local table:

    4.0.0.670