Skip to content

feat: support CosmosDB SDK-type bindings #109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
21 changes: 21 additions & 0 deletions azurefunctions-extensions-bindings-cosmos/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 3 additions & 0 deletions azurefunctions-extensions-bindings-cosmos/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
recursive-include azure *.py *.pyi
recursive-include tests *.py
include LICENSE README.md
105 changes: 105 additions & 0 deletions azurefunctions-extensions-bindings-cosmos/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Azure Functions Extensions Bindings Cosmos library for Python
This library allows Cosmos Input bindings in Python Function Apps to recognize and bind to client types from the
Azure Cosmos sdk.

Cosmos client types can be generated from:

* Cosmos Input

[Source code](https://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-bindings-cosmos)
[Package (PyPi)](https://pypi.org/project/azurefunctions-extensions-bindings-cosmos/)
| API reference documentation
| Product documentation
| [Samples](hhttps://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-bindings-cosmos/samples)


## Getting started

### Prerequisites
* Python 3.9 or later is required to use this package. For more details, please read our page on [Python Functions version support policy](https://learn.microsoft.com/en-us/azure/azure-functions/functions-versions?tabs=isolated-process%2Cv4&pivots=programming-language-python#languages).

* You must have an [Azure subscription](https://azure.microsoft.com/free/) and an
[Azure storage account](https://docs.microsoft.com/azure/storage/common/storage-account-overview) to use this package.

### Install the package
Install the Azure Functions Extensions Bindings Cosmos library for Python with pip:

```bash
pip install azurefunctions-extensions-bindings-cosmos
```

### Create a storage account
If you wish to create a new storage account, you can use the
[Azure Portal](https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-portal),
[Azure PowerShell](https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-powershell),
or [Azure CLI](https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-cli):

```bash
# Create a new resource group to hold the storage account -
# if using an existing resource group, skip this step
az group create --name my-resource-group --location westus2

# Create the storage account
az storage account create -n my-storage-account-name -g my-resource-group
```

### Bind to the SDK-type
The Azure Functions Extensions Bindings Cosmos library for Python allows you to create a function app with
Cosmos Input and define the type as a CosmosClient, DatabaseProxy, or ContainerProxy. Instead of receiving
an InputStream, when the function is executed, the type returned will be the defined SDK-type and have all of the
properties and methods available as seen in the Azure Storage Cosmos library for Python.


```python
import logging
import azure.functions as func
import azurefunctions.extensions.bindings.cosmos as cosmos

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="cosmos")
@app.cosmos_db_input(arg_name="container",
connection="AzureWebJobsStorage",
database_name="db_name",
container_name="container_name")
def get_docs(req: func.HttpRequest, client: cosmos.CosmosClient):
databases = client.list_databases()
for db in databases:
logging.info(f"Found database with ID: {db.get('id')}")

return "ok"
```

## Troubleshooting
### General
The SDK-types raise exceptions defined in [Azure Core](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md).

This list can be used for reference to catch thrown exceptions. To get the specific error code of the exception, use the `error_code` attribute, i.e, `exception.error_code`.

## Next steps

### More sample code

Get started with our [Cosmos samples](hhttps://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-bindings-cosmos/samples).

Several samples are available in this GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Cosmos:

* [cosmos_samples_cosmosclient](https://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-binding-cosmos/samples/cosmos_samples_cosmosclient) - Examples for using the CosmosClient type:
* From CosmosInput

* [cosmos_samples_databaseproxy](https://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-bindings-cosmos/samples/cosmos_samples_databaseproxy) - Examples for using the DatabaseProxy type:
* From CosmosInput

* [cosmos_samples_containerclient](https://github.com/Azure/azure-functions-python-extensions/tree/main/azurefunctions-extensions-bindings-cosmos/samples/cosmos_samples_containerproxy) - Examples for using the ContainerProxy type:
* From CosmosInput

### Additional documentation
For more information on the Azure Cosmos SDK, see the [Azure Cosmos DB documentation](https://learn.microsoft.com/en-us/azure/cosmos-db/) on learn.microsoft.com
and the [Azure Cosmos DB README](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos).

## Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from .cosmosClient import CosmosClient
from .databaseProxy import DatabaseProxy
from .containerProxy import ContainerProxy
from .cosmosClientConverter import CosmosClientConverter

__all__ = [
"CosmosClient",
"DatabaseProxy",
"ContainerProxy",
"CosmosClientConverter"
]

__version__ = "1.0.0b1"
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import json

from azure.identity import DefaultAzureCredential
from azure.cosmos import CosmosClient as CosmosClientSdk, ContainerProxy as ContainerProxySdk
from azurefunctions.extensions.base import Datum, SdkType
from .utils import get_connection_string, using_managed_identity


class ContainerProxy(SdkType):
def __init__(self, *, data: Datum) -> None:
# model_binding_data properties
self._data = data
self._version = None
self._source = None
self._content_type = None
self._database_name = None
self._container_name = None
self._connection = None
self._using_managed_identity = False
self._partition_key = None
self._sql_query = None
self._preferred_locations = None
if self._data:
self._version = data.version
self._source = data.source
self._content_type = data.content_type
content_json = json.loads(data.content)
self._database_name = content_json.get("DatabaseName")
self._container_name = content_json.get("ContainerName")
self._connection = get_connection_string(content_json.get("Connection"))
self._using_managed_identity = using_managed_identity(
content_json.get("Connection")
)
self._preferred_locations = content_json.get("PreferredLocations")

def get_sdk_type(self) -> ContainerProxySdk:
"""
There are two ways to create a CosmosClient:
1. Through the constructor: this is the only option when using Managed Identity
2. Through from_connection_string: this is the only option when not using Managed Identity

We track if Managed Identity is being used through a flag.
"""
if self._data:
cosmos_client = (
CosmosClientSdk(
url=self._connection, credential=DefaultAzureCredential()
)
if self._using_managed_identity
else CosmosClientSdk.from_connection_string(self._connection)
)
db_client = cosmos_client.get_database_client(self._database_name)
return db_client.get_container_client(self._container_name)
else:
return None
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import json

from azure.identity import DefaultAzureCredential
from azure.cosmos import CosmosClient as CosmosClientSdk
from azurefunctions.extensions.base import Datum, SdkType
from .utils import get_connection_string, using_managed_identity


class CosmosClient(SdkType):
def __init__(self, *, data: Datum) -> None:
# model_binding_data properties
self._data = data
self._version = None
self._source = None
self._content_type = None
self._database_name = None
self._container_name = None
self._connection = None
self._using_managed_identity = False
self._partition_key = None
self._sql_query = None
self._preferred_locations = None
if self._data:
self._version = data.version
self._source = data.source
self._content_type = data.content_type
content_json = json.loads(data.content)
self._database_name = content_json.get("DatabaseName")
self._container_name = content_json.get("ContainerName")
self._connection = get_connection_string(content_json.get("Connection"))
self._using_managed_identity = using_managed_identity(
content_json.get("Connection")
)
self._preferred_locations = content_json.get("PreferredLocations")

def get_sdk_type(self) -> CosmosClientSdk:
"""
There are two ways to create a CosmosClient:
1. Through the constructor: this is the only option when using Managed Identity
2. Through from_connection_string: this is the only option when not using Managed Identity

We track if Managed Identity is being used through a flag.
"""
if self._data:
cosmos_client = (
CosmosClientSdk(
url=self._connection, credential=DefaultAzureCredential()
)
if self._using_managed_identity
else CosmosClientSdk.from_connection_string(self._connection)
)
return cosmos_client
else:
return None
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking on this, should we raise an exception if the client cannot be created?

Copy link
Contributor Author

@EvanR-Dev EvanR-Dev Apr 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testing this:
If we return None
Exception: AttributeError: 'NoneType' object has no attribute 'list_databases' - so any operation with the client will throw since it's None

If we raise the exception then the cx will get error message directly and immediately - this is better imo

This should also be done in all the other bindings too - making changes

Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from typing import Any

from azurefunctions.extensions.base import Datum, InConverter, OutConverter

from .cosmosClient import CosmosClient
from .databaseProxy import DatabaseProxy
from .containerProxy import ContainerProxy


class CosmosClientConverter(
InConverter,
OutConverter,
binding="cosmosDB"
):
@classmethod
def check_input_type_annotation(cls, pytype: type) -> bool:
return issubclass(
pytype, (CosmosClient, DatabaseProxy, ContainerProxy)
)

@classmethod
def decode(cls, data: Datum, *, trigger_metadata, pytype) -> Any:
if data is None or data.type is None:
return None

data_type = data.type

if data_type == "model_binding_data":
data = data.value
else:
raise ValueError(
f'unexpected type of data received for the "Cosmos" binding '
f": {data_type!r}"
)

# Determines which sdk type to return based on pytype
if pytype == CosmosClient:
return CosmosClient(data=data).get_sdk_type()
elif pytype == DatabaseProxy:
return DatabaseProxy(data=data).get_sdk_type()
elif pytype == ContainerProxy:
return ContainerProxy(data=data).get_sdk_type()
else:
return None
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import json

from azure.identity import DefaultAzureCredential
from azure.cosmos import CosmosClient as CosmosClientSdk, DatabaseProxy as DatabaseProxySdk
from azurefunctions.extensions.base import Datum, SdkType
from .utils import get_connection_string, using_managed_identity


class DatabaseProxy(SdkType):
def __init__(self, *, data: Datum) -> None:
# model_binding_data properties
self._data = data
self._version = None
self._source = None
self._content_type = None
self._database_name = None
self._container_name = None
self._connection = None
self._using_managed_identity = False
self._partition_key = None
self._sql_query = None
self._preferred_locations = None
if self._data:
self._version = data.version
self._source = data.source
self._content_type = data.content_type
content_json = json.loads(data.content)
self._database_name = content_json.get("DatabaseName")
self._container_name = content_json.get("ContainerName")
self._connection = get_connection_string(content_json.get("Connection"))
self._using_managed_identity = using_managed_identity(
content_json.get("Connection")
)
self._preferred_locations = content_json.get("PreferredLocations")

def get_sdk_type(self) -> DatabaseProxySdk:
"""
There are two ways to create a CosmosClient:
1. Through the constructor: this is the only option when using Managed Identity
2. Through from_connection_string: this is the only option when not using Managed Identity

We track if Managed Identity is being used through a flag.
"""
if self._data:
cosmos_client = (
CosmosClientSdk(
url=self._connection, credential=DefaultAzureCredential()
)
if self._using_managed_identity
else CosmosClientSdk.from_connection_string(self._connection)
)
return cosmos_client.get_database_client(self._database_name)
else:
return None
Loading