Skip to content

Commit 18684df

Browse files
authored
Merge pull request #226854 from vmagelo/function-work-cosmos
Add Python Pivot to Cosmos article where C# and JavaScript already exist
2 parents fa69aa7 + 8df6c2c commit 18684df

File tree

3 files changed

+159
-16
lines changed

3 files changed

+159
-16
lines changed

articles/azure-functions/TOC.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,9 @@
166166
- name: JavaScript
167167
displayName: Connect to a database, Azure Cosmos DB
168168
href: functions-add-output-binding-cosmos-db-vs-code.md?pivots=programming-language-javascript
169+
- name: Python
170+
displayName: Connect to a database, Azure Cosmos DB
171+
href: functions-add-output-binding-cosmos-db-vs-code.md?pivots=programming-language-python
169172
- name: Tutorials
170173
items:
171174
- name: Functions with Logic Apps

articles/azure-functions/functions-add-output-binding-cosmos-db-vs-code.md

Lines changed: 154 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
---
22
title: Connect Azure Functions to Azure Cosmos DB using Visual Studio Code
33
description: Learn how to connect Azure Functions to an Azure Cosmos DB account by adding an output binding to your Visual Studio Code project.
4-
ms.date: 08/17/2021
4+
ms.date: 02/09/2023
55
ms.topic: quickstart
66
zone_pivot_groups: programming-languages-set-functions-temp
7-
ms.devlang: csharp, javascript
7+
ms.devlang: csharp, javascript, python
88
ms.custom: mode-ui, vscode-azure-extension-update-completed, ignite-2022
99
---
1010

@@ -20,6 +20,9 @@ Before you begin, you must complete the [quickstart: Create a C# function in Azu
2020
::: zone pivot="programming-language-javascript"
2121
Before you begin, you must complete the [quickstart: Create a JavaScript function in Azure using Visual Studio Code](create-first-function-vs-code-node.md). If you already cleaned up resources at the end of that article, go through the steps again to recreate the function app and related resources in Azure.
2222
::: zone-end
23+
::: zone pivot="programming-language-python"
24+
Before you begin, you must complete the [quickstart: Create a Python function in Azure using Visual Studio Code](create-first-function-vs-code-python.md). If you already cleaned up resources at the end of that article, go through the steps again to recreate the function app and related resources in Azure.
25+
::: zone-end
2326

2427
## Configure your environment
2528

@@ -30,7 +33,7 @@ Before you get started, make sure to install the [Azure Databases extension](htt
3033
> [!IMPORTANT]
3134
> [Azure Cosmos DB serverless](../cosmos-db/serverless.md) is now generally available. This consumption-based mode makes Azure Cosmos DB a strong option for serverless workloads. To use Azure Cosmos DB in serverless mode, choose **Serverless** as the **Capacity mode** when creating your account.
3235
33-
1. In Visual Studio Code, select **View** > **Command Pallete...** then in the command pallete search for `Azure Databases: Create Server...`
36+
1. In Visual Studio Code, select **View** > **Command Palette...** then in the command palette search for `Azure Databases: Create Server...`
3437

3538
1. Provide the following information at the prompts:
3639

@@ -46,7 +49,7 @@ Before you get started, make sure to install the [Azure Databases extension](htt
4649

4750
## Create an Azure Cosmos DB database and container
4851

49-
1. Select the Azure icon in the Activity bar, expand **Resources** > **Azure Cosmos DB**, right-click (Ctrl+click on macOS) your account, and select **Create database...**.
52+
1. Select the Azure icon in the Activity bar, expand **Resources** > **Azure Cosmos DB**, right-click (Ctrl+select on macOS) your account, and select **Create database...**.
5053

5154
1. Provide the following information at the prompts:
5255

@@ -60,9 +63,9 @@ Before you get started, make sure to install the [Azure Databases extension](htt
6063

6164
## Update your function app settings
6265

63-
In the [previous quickstart article](./create-first-function-vs-code-csharp.md), you created a function app in Azure. In this article, you update your app to write JSON documents to the Azure Cosmos DB container you've just created. To connect to your Azure Cosmos DB account, you must add its connection string to your app settings. You then download the new setting to your local.settings.json file so you can connect to your Azure Cosmos DB account when running locally.
66+
In the [previous quickstart article](./create-first-function-vs-code-csharp.md), you created a function app in Azure. In this article, you update your app to write JSON documents to the Azure Cosmos DB container you've created. To connect to your Azure Cosmos DB account, you must add its connection string to your app settings. You then download the new setting to your local.settings.json file so you can connect to your Azure Cosmos DB account when running locally.
6467

65-
1. In Visual Studio Code, right-click (Ctrl+click on macOS) on your new Azure Cosmos DB account, and select **Copy Connection String**.
68+
1. In Visual Studio Code, right-click (Ctrl+select on macOS) on your new Azure Cosmos DB account, and select **Copy Connection String**.
6669

6770
:::image type="content" source="./media/functions-add-output-binding-cosmos-db-vs-code/copy-connection-string.png" alt-text="Copying the Azure Cosmos DB connection string" border="true":::
6871

@@ -73,7 +76,7 @@ In the [previous quickstart article](./create-first-function-vs-code-csharp.md),
7376
|Prompt| Selection|
7477
|--|--|
7578
|**Enter new app setting name**| Type `CosmosDbConnectionString`.|
76-
|**Enter value for "CosmosDbConnectionString"**| Paste the connection string of your Azure Cosmos DB account you just copied.|
79+
|**Enter value for "CosmosDbConnectionString"**| Paste the connection string of your Azure Cosmos DB account you copied.|
7780

7881
This creates an application setting named connection `CosmosDbConnectionString` in your function app in Azure. Now, you can download this setting to your local.settings.json file.
7982

@@ -89,7 +92,7 @@ Because you're using an Azure Cosmos DB output binding, you must have the corres
8992

9093
::: zone pivot="programming-language-csharp"
9194

92-
With the exception of HTTP and timer triggers, bindings are implemented as extension packages. Run the following [dotnet add package](/dotnet/core/tools/dotnet-add-package) command in the Terminal window to add the Azure Cosmos DB extension package to your project.
95+
Except for HTTP and timer triggers, bindings are implemented as extension packages. Run the following [dotnet add package](/dotnet/core/tools/dotnet-add-package) command in the Terminal window to add the Azure Cosmos DB extension package to your project.
9396

9497
# [In-process](#tab/in-process)
9598
```bash
@@ -102,11 +105,11 @@ dotnet add package Microsoft.Azure.Functions.Worker.Extensions.CosmosDB
102105
---
103106
::: zone-end
104107

105-
::: zone pivot="programming-language-javascript"
108+
::: zone pivot="programming-language-javascript,programming-language-python"
106109

107110
Your project has been configured to use [extension bundles](functions-bindings-register.md#extension-bundles), which automatically installs a predefined set of extension packages.
108111

109-
Extension bundles usage is enabled in the host.json file at the root of the project, which appears as follows:
112+
Extension bundles usage is enabled in the *host.json* file at the root of the project, which appears as follows:
110113

111114
:::code language="json" source="~/functions-quickstart-java/functions-add-output-binding-storage-queue/host.json":::
112115

@@ -116,7 +119,7 @@ Now, you can add the Azure Cosmos DB output binding to your project.
116119

117120
## Add an output binding
118121

119-
In Functions, each type of binding requires a `direction`, `type`, and a unique `name` to be defined in the function.json file. The way you define these attributes depends on the language of your function app.
122+
In Functions, each type of binding requires a `direction`, `type`, and a unique `name` to be defined in the *function.json* file. The way you define these attributes depends on the language of your function app.
120123

121124
::: zone pivot="programming-language-csharp"
122125

@@ -137,7 +140,7 @@ Open the *HttpExample.cs* project file and add the following classes:
137140

138141
:::code language="csharp" source="~/functions-docs-csharp/functions-add-output-binding-cosmos-db-isolated/HttpExample.cs" range="36-46":::
139142

140-
The `MyDocument` class defines an object that gets written to the database. The connection string for the Storage account is set by the `Connection` property. In this case, you could omit `Connection` because you are already using the default storage account.
143+
The `MyDocument` class defines an object that gets written to the database. The connection string for the Storage account is set by the `Connection` property. In this case, you could omit `Connection` because you're already using the default storage account.
141144

142145
The `MultiResponse` class allows you to both write to the specified collection in the Azure Cosmos DB and return an HTTP success message. Because you need to return a `MultiResponse` object, you need to also update the method signature.
143146

@@ -149,9 +152,9 @@ Specific attributes specify the name of the container and the name of its parent
149152

150153
::: zone pivot="programming-language-javascript"
151154

152-
Binding attributes are defined directly in the function.json file. Depending on the binding type, additional properties may be required. The [Azure Cosmos DB output configuration](./functions-bindings-cosmosdb-v2-output.md#configuration) describes the fields required for an Azure Cosmos DB output binding. The extension makes it easy to add bindings to the function.json file.
155+
Binding attributes are defined directly in the *function.json* file. Depending on the binding type, other properties may be required. The [Azure Cosmos DB output configuration](./functions-bindings-cosmosdb-v2-output.md#configuration) describes the fields required for an Azure Cosmos DB output binding. The extension makes it easy to add bindings to the *function.json* file.
153156

154-
To create a binding, right-click (Ctrl+click on macOS) the `function.json` file in your HttpTrigger folder and choose **Add binding...**. Follow the prompts to define the following binding properties for the new binding:
157+
To create a binding, right-click (Ctrl+select on macOS) the *function.json* file in your HttpTrigger folder and choose **Add binding...**. Follow the prompts to define the following binding properties for the new binding:
155158

156159
| Prompt | Value | Description |
157160
| -------- | ----- | ----------- |
@@ -165,7 +168,7 @@ To create a binding, right-click (Ctrl+click on macOS) the `function.json` file
165168
| **Partition key (optional)** | *leave blank* | Only required when the output binding creates the container. |
166169
| **Collection throughput (optional)** | *leave blank* | Only required when the output binding creates the container. |
167170

168-
A binding is added to the `bindings` array in your function.json, which should look like the following after removing any `undefined` values present
171+
A binding is added to the `bindings` array in your *function.json*, which should look like the following after removing any `undefined` values present
169172

170173
```json
171174
{
@@ -181,6 +184,57 @@ A binding is added to the `bindings` array in your function.json, which should l
181184

182185
::: zone-end
183186

187+
::: zone pivot="programming-language-python"
188+
189+
The way that you define the new binding depends on your Python programming model.
190+
191+
# [v1](#tab/v1)
192+
193+
Binding attributes are defined directly in the *function.json* file. Depending on the binding type, other properties may be required. The [Azure Cosmos DB output configuration](./functions-bindings-cosmosdb-v2-output.md#configuration) describes the fields required for an Azure Cosmos DB output binding. The extension makes it easy to add bindings to the *function.json* file.
194+
195+
To create a binding, right-select (Ctrl+select on macOS) the *function.json* file in your HttpTrigger folder and choose **Add binding...**. Follow the prompts to define the following binding properties for the new binding:
196+
197+
| Prompt | Value | Description |
198+
| -------- | ----- | ----------- |
199+
| **Select binding direction** | `out` | The binding is an output binding. |
200+
| **Select binding with direction "out"** | `Azure Cosmos DB` | The binding is an Azure Cosmos DB binding. |
201+
| **The name used to identify this binding in your code** | `outputDocument` | Name that identifies the binding parameter referenced in your code. |
202+
| **The Azure Cosmos DB database where data will be written** | `my-database` | The name of the Azure Cosmos DB database containing the target container. |
203+
| **Database collection where data will be written** | `my-container` | The name of the Azure Cosmos DB container where the JSON documents will be written. |
204+
| **If true, creates the Azure Cosmos DB database and collection** | `false` | The target database and container already exist. |
205+
| **Select setting from "local.setting.json"** | `CosmosDbConnectionString` | The name of an application setting that contains the connection string for the Azure Cosmos DB account. |
206+
| **Partition key (optional)** | *leave blank* | Only required when the output binding creates the container. |
207+
| **Collection throughput (optional)** | *leave blank* | Only required when the output binding creates the container. |
208+
209+
A binding is added to the `bindings` array in your *function.json*, which should look like the following after removing any `undefined` values present
210+
211+
```json
212+
{
213+
"type": "cosmosDB",
214+
"direction": "out",
215+
"name": "outputDocument",
216+
"databaseName": "my-database",
217+
"collectionName": "my-container",
218+
"createIfNotExists": "false",
219+
"connectionStringSetting": "CosmosDbConnectionString"
220+
}
221+
```
222+
223+
# [v2](#tab/v2)
224+
225+
Binding attributes are defined directly in the *function_app.py* file. You use the `cosmos_db_output` decorator to add an [Azure Cosmos DB output binding](/azure/azure-functions/functions-bindings-triggers-python#azure-cosmos-db-output-binding):
226+
227+
```python
228+
@app.cosmos_db_output(arg_name="outputDocument", database_name="my-database",
229+
collection_name="my-container", connection_string_setting="CosmosDbConnectionString")
230+
```
231+
232+
In this code, `arg_name` identifies the binding parameter referenced in your code, `database_name` and `collection_name` are the database and collection names that the binding writes to, and `connection_string_setting` is the name of an application setting that contains the connection string for the Storage account, which is in the CosmosDbConnectionString setting in the *local.settings.json* file.
233+
234+
---
235+
236+
::: zone-end
237+
184238
## Add code that uses the output binding
185239

186240
::: zone pivot="programming-language-csharp"
@@ -295,11 +349,90 @@ This code now returns a `MultiResponse` object that contains both a document and
295349

296350
::: zone-end
297351

352+
::: zone pivot="programming-language-python"
353+
354+
# [v1](#tab/v1)
355+
356+
Update *HttpExample\\\_\_init\_\_.py* to match the following code. Add the `outputDocument` parameter to the function definition and `outputDocument.set()` under the `if name:` statement:
357+
358+
```python
359+
import azure.functions as func
360+
import logging
361+
362+
def main(req: func.HttpRequest, msg: func.Out[func.QueueMessage],
363+
outputDocument: func.Out[func.Document]) -> str:
364+
365+
name = req.params.get('name')
366+
if not name:
367+
try:
368+
req_body = req.get_json()
369+
except ValueError:
370+
pass
371+
else:
372+
name = req_body.get('name')
373+
374+
if name:
375+
outputDocument.set(func.Document.from_dict({"id": name}))
376+
msg.set(name)
377+
return func.HttpResponse(f"Hello {name}!")
378+
else:
379+
return func.HttpResponse(
380+
"Please pass a name on the query string or in the request body",
381+
status_code=400
382+
)
383+
```
384+
385+
The document `{"id": "name"}` is created in the database collection specified in the binding.
386+
387+
# [v2](#tab/v2)
388+
389+
Update *HttpExample\\function_app.py* to match the following code. Add the `outputDocument` parameter to the function definition and `outputDocument.set()` under the `if name:` statement:
390+
391+
```python
392+
import azure.functions as func
393+
import logging
394+
395+
app = func.FunctionApp()
396+
397+
@app.function_name(name="HttpTrigger1")
398+
@app.route(route="hello", auth_level=func.AuthLevel.ANONYMOUS)
399+
@app.queue_output(arg_name="msg", queue_name="outqueue", connection="AzureWebJobsStorage")
400+
@app.cosmos_db_output(arg_name="outputDocument", database_name="my-database", collection_name="my-container" connection_string_setting="CosmosDbConnectionString")
401+
def test_function(req: func.HttpRequest, msg: func.Out[func.QueueMessage],
402+
outputDocument: func.Out[func.Document]) -> func.HttpResponse:
403+
logging.info('Python HTTP trigger function processed a request.')
404+
logging.info('Python Cosmos DB trigger function processed a request.')
405+
name = req.params.get('name')
406+
if not name:
407+
try:
408+
req_body = req.get_json()
409+
except ValueError:
410+
pass
411+
else:
412+
name = req_body.get('name')
413+
414+
if name:
415+
outputDocument.set(func.Document.from_dict({"id": name}))
416+
msg.set(name)
417+
return func.HttpResponse(f"Hello {name}!")
418+
else:
419+
return func.HttpResponse(
420+
"Please pass a name on the query string or in the request body",
421+
status_code=400
422+
)
423+
```
424+
425+
The document `{"id": "name"}` is created in the database collection specified in the binding.
426+
427+
---
428+
429+
::: zone-end
430+
298431
::: zone pivot="programming-language-csharp"
299432
[!INCLUDE [functions-run-function-test-local-vs-code-csharp](../../includes/functions-run-function-test-local-vs-code-csharp.md)]
300433
::: zone-end
301434

302-
::: zone pivot="programming-language-javascript"
435+
::: zone pivot="programming-language-javascript,programming-language-python"
303436
## Run the function locally
304437

305438
1. As in the previous article, press <kbd>F5</kbd> to start the function app project and Core Tools.
@@ -358,3 +491,8 @@ You've updated your HTTP triggered function to write JSON documents to an Azure
358491

359492
+ [Azure Functions JavaScript developer guide](functions-reference-node.md)
360493
::: zone-end
494+
::: zone pivot="programming-language-python"
495+
+ [Examples of complete Function projects in Python](/samples/browse/?products=azure-functions&languages=python).
496+
497+
+ [Azure Functions Python developer guide](functions-reference-node.md)
498+
::: zone-end

articles/zone-pivot-groups.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,8 @@ groups:
335335
title: C#
336336
- id: programming-language-javascript
337337
title: JavaScript
338+
- id: programming-language-python
339+
title: Python
338340
- id: programming-languages-set-functions-full
339341
title: Programming languages
340342
prompt: Choose a programming language

0 commit comments

Comments
 (0)