Skip to content

Instantly share code, notes, and snippets.

@adamfortuno
Last active September 9, 2022 02:12
Show Gist options
  • Save adamfortuno/87259afaf222acf587f75533b3958fab to your computer and use it in GitHub Desktop.
Save adamfortuno/87259afaf222acf587f75533b3958fab to your computer and use it in GitHub Desktop.
Connect to an Astra DB Serverless database over the cqlsh Interface Using the cassandra module for Python
import logging
import azure.functions as func
import os
from pathlib import Path
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Executing function `insert_data_cqlsh`...')
status_code = 200
output = "No output received."
try:
script_path = os.path.abspath(os.path.dirname(__file__))
scb_path = f"{script_path}/secure-connect-silverfish.zip"
## The module decompresses the secure-connection-bundle when establishing a
## connection. Since the file system in Azure Functions is readonly by default,
## you want to set the `use_default_tempdir` in the dictionary passed to the
## Cluster object's constructor.
cloud_config = { 'secure_connect_bundle': scb_path, 'use_default_tempdir': True }
logging.info(f"The SCB is in `{cloud_config}`.")
auth_provider = PlainTextAuthProvider(
'*********',
'*********'
)
logging.info('Connecting to the cluster...')
cluster = Cluster(cloud = cloud_config, auth_provider = auth_provider)
session = cluster.connect()
logging.info('Executing `select` statement...')
row = session.execute("select release_version from system.local").one()
if row:
output = row[0]
logging.info('Processing concluded...')
except Exception as err:
status_code = 500
output = repr(err)
logging.info(output)
return func.HttpResponse(
output,
status_code = status_code
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment