Integrate Azure Functions with Astra DB Serverless
Azure Functions is Microsoft Azure’s function-as-a-service offering that provides a serverless execution environment for your code. You can use Azure Functions for actions such as the following:
-
Extend Astra DB Serverless with additional data processing capabilities, such as aggregating, summarizing, and validating data periodically.
-
Connect Astra DB Serverless with other cloud services into data pipelines that move, process, and analyze data.
Prerequisites
-
An active Astra DB Serverless database.
-
An application token with the Database Administrator role.
-
The Secure Connect Bundle (SCB) for your database.
-
Python 3.10 or later
Create a local Azure Functions project
Create a local project, based on the Azure Functions Python quickstart, to develop and test your Azure Functions before you deploy them to the cloud.
-
Install the Azure CLI.
-
Install the Azure functions core tools package version 4.0 or later.
-
Create and activate a new Python virtual environment:
python -m venv .venv source .venv/bin/activate -
Initialize a new Azure Functions project with the Python runtime:
func init --pythonThis command initializes a project directory with a
function_app.pyfile, arequirements.txtfile, and other necessary Python files. -
Use
func newto add a function to your project:func new --name HttpExample --template "HTTP trigger" --authlevel "ANONYMOUS"The
--nameargument is the unique name of your function, and the--templateargument specifies the function’s trigger.In this example,
func newadds an HTTP trigger endpoint namedHttpExampleto thefunction_app.pyfile, which is accessible without authentication. For more information, see the Azure functionapp CLI reference. -
Replace the contents of
function_app.pywith the following code:import azure.functions as func import datetime import json import logging app = func.FunctionApp() @app.route(route="HttpExample", auth_level=func.AuthLevel.ANONYMOUS) def HttpExample(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') name = req.params.get('name') if not name: try: req_body = req.get_json() except ValueError: pass else: name = req_body.get('name') if name: return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.") else: return func.HttpResponse( "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.", status_code=200 ) -
Run the function locally:
func startFrom the output, use the
HttpExampleinvoke URL to trigger the function. The expected output is the contents offunc.HttpResponsefrom thefunction_app.pyscript.Azure Functions Core Tools Core Tools Version: 4.0.5907 Commit hash: N/A +807e89766a92b14fd07b9f0bc2bea1d8777ab209 (64-bit) Function Runtime Version: 4.834.3.22875 [2024-07-25T14:48:34.922Z] Worker process started and initialized. Functions: HttpExample: http://localhost:7071/api/HttpExampleIf you get a
No job functions founderror, open your project’slocal.settings.jsonfile, and then make sureUseDevelopmentStorageis set totrue:{ "IsEncrypted": false, "Values": { "FUNCTIONS_WORKER_RUNTIME": "python", "AzureWebJobsFeatureFlags": "EnableWorkerIndexing", "AzureWebJobsStorage": "UseDevelopmentStorage=true" } }
Deploy the function to the cloud
-
Sign into your Azure account:
az login -
Create a resource group, specifying the group name and region code.
For this example, the group is named
AzureFunctionsQuickstartand the location iseastus2:az group create --name AzureFunctionsQuickstart --location eastus2To get region codes, run the
az account list-locationscommand. In the next steps, you will deploy the function to the same region. -
Create a general-purpose storage account (
--sku Standard_LRS) using the resource group and region from the previous step.For this example, the storage account is named
astraquickstartstorage:az storage account create --name astraquickstartstorage --location eastus2 --resource-group AzureFunctionsQuickstart --sku Standard_LRSFor more information, see Storage considerations for Azure Functions.
-
Create the function app in Azure with
az functionapp createand the resource group, region, and storage account from the previous steps:az functionapp create --resource-group AzureFunctionsQuickstart --consumption-plan-location eastus2 --runtime python --runtime-version 3.10 --functions-version 4 --name uniqueapplication --os-type linux --storage-account astraquickstartstorageFor this example,
--os-type linuxis required because Python functions only run on Linux. -
Publish the application in Azure to make it publicly available and get the application’s endpoint:
func azure functionapp publish uniqueapplication -
To test the deployed application, send a request to the application’s endpoint:
curl "https://uniqueapplication.azurewebsites.net/api/HttpExample?name=datastax"The output uses the value of the
namequery parameter:Hello, datastax. This HTTP triggered function executed successfully.You can also view, test, and debug the function in the Azure portal.
Create the Azure function with the Cassandra Python driver
Now that you have a working template application, locally modify the application to connect to Astra DB with the Cassandra Python driver, and the republish the application:
-
Set the following environment variables:
export APP_NAME = # Function app name export RESOURCE_GROUP_NAME = # Azure resource group name export ASTRA_DB_CLIENT_ID = token # The literal string 'token' export ASTRA_DB_CLIENT_SECRET = # Astra application token (AstraCS:...) -
Use the Azure CLI or Azure Portal to add
ASTRA_DB_CLIENT_IDandASTRA_DB_CLIENT_SECRETto the application settings:az functionapp config appsettings set \ --name ${APP_NAME} \ --resource-group ${RESOURCE_GROUP_NAME} \ --settings "ASTRA_DB_CLIENT_ID=${ASTRA_DB_CLIENT_ID}" az functionapp config appsettings set \ --name ${APP_NAME} \ --resource-group ${RESOURCE_GROUP_NAME} \ --settings "ASTRA_DB_CLIENT_SECRET=${ASTRA_DB_CLIENT_SECRET}" -
In your Python project, add the Python driver (
cassandra-driver) to therequirements.txtfile:echo "cassandra-driver" | cat >> requirements.txt cat requirements.txt -
Replace the
function_app.pycontent with the following code, and then replacesecure-connect-bundle-for-your-database.zipwith the file name for your database’s SCB.For this example, the SCB is stored at the root of the Python project directory. In production, treat the SCB as a secret. For example, use an Azure Key Vault reference in your app settings.
This function connects to your database using the Python driver and retrieves the supported CQL version from the
system.localtable. The output is formatted asVERSION Success, such as3.4.5 Success.import azure.functions as func from azure.functions import AuthLevel import datetime import json import logging import os from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider ASTRA_DB_CLIENT_ID = os.environ.get('ASTRA_DB_CLIENT_ID') ASTRA_DB_CLIENT_SECRET = os.environ.get('ASTRA_DB_CLIENT_SECRET') if not ASTRA_DB_CLIENT_ID or not ASTRA_DB_CLIENT_SECRET: raise ValueError("Environment variables ASTRA_DB_CLIENT_ID and ASTRA_DB_CLIENT_SECRET must be set") cloud_config = { 'secure_connect_bundle': 'secure-connect-bundle-for-your-database.zip', 'use_default_tempdir': True } auth_provider = PlainTextAuthProvider(ASTRA_DB_CLIENT_ID, ASTRA_DB_CLIENT_SECRET) cluster = Cluster( cloud=cloud_config, auth_provider=auth_provider, protocol_version=4 ) app = func.FunctionApp() @app.route(route="HttpExample", auth_level=func.AuthLevel.ANONYMOUS) def HttpExample(req: func.HttpRequest) -> func.HttpResponse: session = cluster.connect() session.default_timeout = 60 row = session.execute("SELECT cql_version FROM system.local WHERE key = 'local';").one() cql_version = row[0] logging.info(f"{cql_version} Success") return func.HttpResponse(f"{cql_version} Success") -
Test the function locally:
-
Start the Azure Functions runtime:
func start -
Use the returned
HttpExampleinvoke URL to trigger the function:Azure Functions Core Tools Core Tools Version: 4.0.5907 Commit hash: N/A +807e89766a92b14fd07b9f0bc2bea1d8777ab209 (64-bit) Function Runtime Version: 4.834.3.22875 [2024-07-25T14:48:34.922Z] Worker process started and initialized. Functions: HttpExample: http://localhost:7071/api/HttpExampleFor this example, a successful response is
VERSION Success, such as3.4.5 Success.
-
-
Deploy the updated function to Azure:
func azure functionapp publish uniqueapplicationA successful build returns
Remote build succeededand an invoke URL for your application. -
To test your application, send a
GETrequest to your application’s invoke URL:curl "https://uniqueapplication.azurewebsites.net/api/HttpExample"This Azure function integrates with Astra DB Serverless through the Cassandra Python driver. Try extending or modifying the function to run queries against your database. For more information, see the Python driver documentation.