Connect with Python#
This example connects to an Aiven for Apache Cassandra® service from Python as the avnadmin
user by making use of the cassandra-driver
library.
Pre-requisites#
Install the cassandra-driver
library:
pip install cassandra-driver
Variables#
These are the placeholders you will need to replace in the code sample:
Variable |
Description |
---|---|
|
Host name of your Cassandra service. |
|
Port number used for connecting to your Cassandra service |
|
Username used for connecting to your Cassandra service. Defaults to |
|
Password of the |
|
Path to the CA Certificate file of your Cassandra service |
Tip
The Aiven for Cassandra CA certificate can be downloaded from Aiven Console, on the service detail page or with the dedicated Aiven CLI command.
Connect to the database#
The following example establishes a SSL connection with your database cluster; replace the placeholders for HOST
, PORT
, USER
, PASSWORD
, SSL-CERTFILE
:
import ssl
from cassandra.auth import PlainTextAuthProvider
from cassandra.cluster import Cluster
from cassandra.policies import DCAwareRoundRobinPolicy
auth_provider = PlainTextAuthProvider(USER, PASSWORD)
ssl_options = {"ca_certs": SSL_CERTFILE, "cert_reqs": ssl.CERT_REQUIRED}
with Cluster([HOST], port=PORT, ssl_options=ssl_options, auth_provider=auth_provider,
load_balancing_policy=DCAwareRoundRobinPolicy(local_dc='aiven')) as cluster:
with cluster.connect() as session:
# Here you can now read from or write to the database