DataStax Python driver
Before using a DataStax driver, review Best practices for DataStax drivers and upgrade or install the latest supported driver for your language. For more details about supported software, see the DataStax Support Policy.
Upgrade your driver to a compatible version to connect to Astra DB databases. For more information, see the DataStax Driver Matrix. |
Connect the Python driver
-
Create a database, and then set environment variables for database ID, region, and keyspace.
-
Create an application token, and then set a token environment variable.
The
token.json
has the following format:{ "clientId": "CLIENT_ID", "secret": "CLIENT_SECRET", "token": "APPLICATION_TOKEN" }
For authentication with the driver, you can use either
clientId
andsecret
or the literal stringtoken
and theAstraCS
token value. If you are on an older driver version that doesn’t supporttoken
andAstraCS
, then you might need to useclientId
andsecret
. -
Download your database’s Secure Connect Bundle (SCB).
-
Download and install a supported Python version. Python 3.4, 3.5, 3.6, 3.7, and 3.8 are supported, and CPython (the standard Python implementation) and PyPy are supported and tested.
-
Install the DataStax Python driver:
pip install cassandra-driver
See the Python driver installation instructions for more information.
-
Verify that the DataStax Python driver installed successfully:
python -c 'import cassandra; print (cassandra.__version__)'
Make sure the returned version number is
3.24.0
or later. -
Create a
connect_database.py
file in the main directory for your Python project:cd python_project touch connect_database.py
-
Enter the following connection code in your script.
Set the
cloud_config
parameter for theCluster
initialization as shown in the following example. Thesecure_connect_bundle
must include the absolute path to your Astra DB database credentials (secure-connect-DATABASE_NAME.zip
).connect_database.pyfrom cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider import json with open(ASTRA_TOKEN_PATH, "r") as f: creds = json.load(f) ASTRA_DB_APPLICATION_TOKEN = creds["token"] cluster = Cluster( cloud={ "secure_connect_bundle": ASTRA_DB_SECURE_BUNDLE_PATH, }, auth_provider=PlainTextAuthProvider( "token", ASTRA_DB_APPLICATION_TOKEN, ), ) session = cluster.connect()
-
Add code to create a
Cluster
instance to connect to your Astra DB database, run a CQL query, and print the output to the console. You will typically have one instance of Cluster for each Astra DB database that you want to interact with.connect_database.pyrow = session.execute("select release_version from system.local").one() if row: print(row[0]) else: print("An error occurred.")
-
Save your script, and then run it:
python ./connect_database.py