Skip to main content

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.

Prerequisites

Install the cassandra-driver library:

pip install cassandra-driver

Variables

These are the placeholders you will need to replace in the code sample:

VariableDescription
HOSTHost name of your Cassandra service.
PORTPort number used for connecting to your Cassandra service
USERUsername used for connecting to your Cassandra service. Defaults to avnadmin
PASSWORDPassword of the avnadmin user
SSL-CERTFILEPath 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.

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