Skip to content

Instantly share code, notes, and snippets.

@omnifroodle
Last active October 30, 2020 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omnifroodle/cd82691c4a0b02117b46c41b9e4c196b to your computer and use it in GitHub Desktop.
Save omnifroodle/cd82691c4a0b02117b46c41b9e4c196b to your computer and use it in GitHub Desktop.
Connecting to Astra with Older Python libs

Working backwards with Astra and Python/Flask/Django

So you heard about this awesome new hosted Cassandra and wanted to kick the tires? But after setting up your favorite stack you realize that the secure connect bundle from Astra doesn’t seem to plug in anywhere. Suddenly easy doesn’t seem so easy anymore.

I’m going to walk you through one example of how you can connect an older CQL library to Astra. In this case we’ll be using Flask and CQLAlchemy. CQLAlchemy has something of a following in the Flask/Cassandra world but hasn’t seen an update in a while.

First, unzip the secure bundle you downloaded from Astra. You should see something like this:

$ ls secure-connect
ca.crt         cert           cert.pfx       config.json    cqlshrc        identity.jks   key            trustStore.jks

Everything you need to connect using a legacy driver is here. I’ll call out a few key files you’ll need to get connected. In the config.json we’ll find information about the host, port and keyspace we’ll need to connect. We’ll also need the following files to setup our secure connection to Astra ca.crt, cert, and key.

Lets assume the following values from your config.json:

{
  "host": "abc-123-us-east1.db.astra.datastax.com",
  "port": 31434,
  ...
  "keyspace": "sg",
  ...
}

If you unzip your secure bundle in your flask project directory and re-name the folder secure-connect then the following code should allow you to connect:

from flask import Flask
from flask_cqlalchemy import CQLAlchemy
from ssl import SSLContext, PROTOCOL_TLS, CERT_REQUIRED
from cassandra.auth import PlainTextAuthProvider

ssl_context = SSLContext(PROTOCOL_TLS)
ssl_context.load_verify_locations("secure-connect/ca.crt")
ssl_context.verify_mode = CERT_REQUIRED
ssl_context.load_cert_chain(certfile="secure-connect/cert", keyfile="secure-connect/key")
auth_provider = PlainTextAuthProvider(username='dbadmin', password='dbpassword')

app = Flask(__name__)
app.config['CASSANDRA_HOSTS'] = ['abc-123-us-east1.db.astra.datastax.com']
app.config['CASSANDRA_SETUP_KWARGS'] = dict(ssl_context=ssl_context, port="31434", auth_provider=auth_provider)
app.config['CASSANDRA_KEYSPACE'] = "sg"
db = CQLAlchemy(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment