Connect the Python driver to your database
DataStax recommends using the Python client with Serverless (Vector) databases. Use the Python driver only if you are working with an existing application that previously used a CQL-based driver or if you plan to explicitly use CQL. |
Select one of the following methods for connecting the Python driver to your database.
Prerequisite
Download a secure connect bundle from the Astra Portal.
Basic configuration
This configuration is recommended for basic use cases that are not proofs of concept or production use.
It initializes a session for connecting to your database using the cassandra-driver
and sets up the connection with a secure connect bundle and authentication details sourced from environment variables.
import os
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
session = Cluster(
cloud={"secure_connect_bundle": os.environ["ASTRA_DB_SECURE_BUNDLE_PATH"]},
auth_provider=PlainTextAuthProvider("token", os.environ["ASTRA_DB_APPLICATION_TOKEN"]),
).connect()
Production configuration
This configuration is for proofs of concept or production use. This code example includes additional configurations for connection timeout, request timeout, and protocol version.
from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT, ProtocolVersion
cloud_config= {
'secure_connect_bundle': os.environ["ASTRA_DB_SECURE_BUNDLE_PATH"],
'connect_timeout': 30
}
auth_provider=PlainTextAuthProvider("token", os.environ["ASTRA_DB_APPLICATION_TOKEN"])
profile = ExecutionProfile(request_timeout=30)
cluster = Cluster(
cloud=cloud_config,
auth_provider=auth_provider,
execution_profiles={EXEC_PROFILE_DEFAULT: profile},
protocol_version=ProtocolVersion.V4
)
session = cluster.connect()
See the Python quickstart for details on how to install the package, connect to a Serverless (Vector) database, create a table and vector-compatible Storage-Attached Index (SAI), load data, and perform a similarity search.