Skip to content

Commit 9b6380d

Browse files
Merge pull request #271529 from wmwxwa/patch-16
Update Cosmos DB connector in functions-reference-python.md
2 parents 9a8b8ac + 0b934fe commit 9b6380d

File tree

1 file changed

+38
-34
lines changed

1 file changed

+38
-34
lines changed

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

Lines changed: 38 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -219,10 +219,13 @@ When you deploy your project to a function app in Azure, the entire contents of
219219
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:
220220

221221
```python
222-
pip install azure-cosmos
222+
pip install azure-cosmos
223+
pip install aiohttp
223224

224-
from azure.cosmos import CosmosClient, exceptions
225+
from azure.cosmos.aio import CosmosClient
226+
from azure.cosmos import exceptions
225227
from azure.cosmos.partition_key import PartitionKey
228+
import asyncio
226229

227230
# Replace these values with your Cosmos DB connection information
228231
endpoint = "https://azure-cosmos-nosql.documents.azure.com:443/"
@@ -234,41 +237,42 @@ partition_key = "/partition_key"
234237
# Set the total throughput (RU/s) for the database and container
235238
database_throughput = 1000
236239

237-
# Initialize the Cosmos client
238-
client = CosmosClient(endpoint, key)
240+
# Helper function to get or create database and container
241+
async def get_or_create_container(client, database_id, container_id, partition_key):
239242

240-
# Create or get a reference to a database
241-
try:
242-
database = client.create_database_if_not_exists(id=database_id)
243+
database = await client.create_database_if_not_exists(id=database_id)
243244
print(f'Database "{database_id}" created or retrieved successfully.')
244245

245-
except exceptions.CosmosResourceExistsError:
246-
database = client.get_database_client(database_id)
247-
print('Database with id \'{0}\' was found'.format(database_id))
248-
249-
# Create or get a reference to a container
250-
try:
251-
container = database.create_container(id=container_id, partition_key=PartitionKey(path='/partitionKey'))
252-
print('Container with id \'{0}\' created'.format(container_id))
253-
254-
except exceptions.CosmosResourceExistsError:
255-
container = database.get_container_client(container_id)
256-
print('Container with id \'{0}\' was found'.format(container_id))
257-
258-
# Sample document data
259-
sample_document = {
260-
"id": "1",
261-
"name": "Doe Smith",
262-
"city": "New York",
263-
"partition_key": "NY"
264-
}
265-
266-
# Insert a document
267-
container.create_item(body=sample_document)
268-
269-
# Query for documents
270-
query = "SELECT * FROM c where c.id = 1"
271-
items = list(container.query_items(query, enable_cross_partition_query=True))
246+
container = await database.create_container_if_not_exists(id=container_id, partition_key=PartitionKey(path=partition_key))
247+
print(f'Container with id "{container_id}" created')
248+
249+
return container
250+
251+
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+
261+
async def get_products():
262+
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)
267+
return items
268+
269+
async def main():
270+
await create_products()
271+
products = await get_products()
272+
print(products)
273+
274+
if __name__ == "__main__":
275+
asyncio.run(main())
272276
```
273277

274278
::: zone pivot="python-mode-decorators"

0 commit comments

Comments
 (0)