Connecting to your database with the DataStax Python driver

Use the DataStax Python driver to connect to your cluster created using the DataStax Cloud console.

Use the unified DataStax Python driver to connect to your DataStax Astra database and begin building your own application.
Tip: 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 databases.

Prerequisites

  1. Download and install a supported Python version. Python 2.7, 3.4, 3.5 and 3.6 are supported.
    Note: CPython (the standard Python implementation) and PyPy are supported and tested.
  2. Download the secure connect bundle to obtain connection credentials for your DataStax Astra database.

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

What's next

Build your application. See the DataStax Python driver documentation for more information about using the DataStax Python driver.