Skip to content

Commit 698fe9b

Browse files
Merge pull request #271701 from wmwxwa/patch-17
Functions+Cosmos integration & Cosmos async SDK+singleton functions-r…
2 parents 8dc8831 + ff37f74 commit 698fe9b

File tree

1 file changed

+36
-19
lines changed

1 file changed

+36
-19
lines changed

articles/azure-functions/functions-reference-python.md

Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -214,9 +214,15 @@ When you deploy your project to a function app in Azure, the entire contents of
214214

215215
## Connect to a database
216216

217-
[Azure Cosmos DB](../cosmos-db/introduction.md) is a fully managed NoSQL, relational, and vector database for modern app development including AI, digital commerce, Internet of Things, booking management, and other types of solutions. It offers single-digit millisecond response times, automatic and instant scalability, and guaranteed speed at any scale. Its various APIs can accommodate all your operational data models, including relational, document, vector, key-value, graph, and table.
217+
Azure Functions integrates well with [Azure Cosmos DB](../cosmos-db/introduction.md) for many [use cases](../cosmos-db/use-cases.md), including IoT, ecommerce, gaming, etc.
218218

219-
To connect to Cosmos DB, first [create an account, database, and container](../cosmos-db/nosql/quickstart-portal.md). Then you may connect Functions to Cosmos DB using [trigger and bindings](functions-bindings-cosmosdb-v2.md), like this [example](functions-add-output-binding-cosmos-db-vs-code.md). You may also use the Python library for Cosmos DB, like so:
219+
For example, for [event sourcing](https://learn.microsoft.com/azure/architecture/patterns/event-sourcing), the two services are integrated to power event-driven architectures using Azure Cosmos DB's [change feed](../cosmos-db/change-feed.md) functionality. The change feed provides downstream microservices the ability to reliably and incrementally read inserts and updates (for example, order events). This functionality can be leveraged to provide a persistent event store as a message broker for state-changing events and drive order processing workflow between many microservices (which can be implemented as [serverless Azure Functions](https://azure.com/serverless)).
220+
221+
:::image type="content" source="../cosmos-db/media/use-cases/event-sourcing.png" alt-text="Azure Cosmos DB ordering pipeline reference architecture" border="false":::
222+
223+
To connect to Cosmos DB, first [create an account, database, and container](../cosmos-db/nosql/quickstart-portal.md). Then you may connect Functions to Cosmos DB using [trigger and bindings](functions-bindings-cosmosdb-v2.md), like this [example](functions-add-output-binding-cosmos-db-vs-code.md).
224+
225+
To implement more complex app logic, you may also use the Python library for Cosmos DB. An aynchronous I/O implementation looks like this:
220226

221227
```python
222228
pip install azure-cosmos
@@ -237,9 +243,11 @@ partition_key = "/partition_key"
237243
# Set the total throughput (RU/s) for the database and container
238244
database_throughput = 1000
239245

246+
# Singleton CosmosClient instance
247+
client = CosmosClient(endpoint, credential=key)
248+
240249
# Helper function to get or create database and container
241250
async def get_or_create_container(client, database_id, container_id, partition_key):
242-
243251
database = await client.create_database_if_not_exists(id=database_id)
244252
print(f'Database "{database_id}" created or retrieved successfully.')
245253

@@ -249,28 +257,37 @@ async def get_or_create_container(client, database_id, container_id, partition_k
249257
return container
250258

251259
async def create_products():
252-
async with CosmosClient(endpoint, credential=key) as client:
253-
container = await get_or_create_container(client, database_id, container_id, partition_key)
254-
for i in range(10):
255-
await container.upsert_item({
256-
'id': f'item{i}',
257-
'productName': 'Widget',
258-
'productModel': f'Model {i}'
259-
})
260+
container = await get_or_create_container(client, database_id, container_id, partition_key)
261+
for i in range(10):
262+
await container.upsert_item({
263+
'id': f'item{i}',
264+
'productName': 'Widget',
265+
'productModel': f'Model {i}'
266+
})
260267

261268
async def get_products():
262269
items = []
263-
async with CosmosClient(endpoint, credential=key) as client:
264-
container = await get_or_create_container(client, database_id, container_id, partition_key)
265-
async for item in container.read_all_items():
266-
items.append(item)
270+
container = await get_or_create_container(client, database_id, container_id, partition_key)
271+
async for item in container.read_all_items():
272+
items.append(item)
267273
return items
268-
274+
275+
async def query_products(product_name):
276+
container = await get_or_create_container(client, database_id, container_id, partition_key)
277+
query = f"SELECT * FROM c WHERE c.productName = '{product_name}'"
278+
items = []
279+
async for item in container.query_items(query=query, enable_cross_partition_query=True):
280+
items.append(item)
281+
return items
282+
269283
async def main():
270284
await create_products()
271-
products = await get_products()
272-
print(products)
273-
285+
all_products = await get_products()
286+
print('All Products:', all_products)
287+
288+
queried_products = await query_products('Widget')
289+
print('Queried Products:', queried_products)
290+
274291
if __name__ == "__main__":
275292
asyncio.run(main())
276293
```

0 commit comments

Comments
 (0)