关于HHTPTrigger从CosmosDB检索文档

时间:2020-06-03 02:26:36

标签: azure-functions

我正在尝试执行HTTP触发器azure函数以从CosmosDB中检索文档。我正在尝试在URL中传递id值,但无法检索该文档。我已经从docs.microsoft.com获得了此示例代码。

功能代码:

import logging
import azure.functions as func
def main(req: func.HttpRequest, todoitems: func.DocumentList) -> str:
    if not todoitems:
        logging.warning("ToDo item not found")
    else:
        logging.info("Found ToDo item, Description=%s",
                     todoitems[0]['description'])

    return 'OK'

function.json

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "cosmosDB",
      "name": "todoitems",
      "databaseName": "ckdb",
      "collectionName": "cosmocontainer",
      "connectionStringSetting": "ckdb_DOCUMENTDB",
      "direction": "in",
      "id": "{id}",
      "PartitionKey": "{id}"
    }
  ],
  "disabled": true,
  "scriptFile": "__init__.py"
} 

URL:

http://localhost:7071/api/HttpTrigger1?id="3"

即使我在cosmosdb数据库中具有id值为“ 3”的文档,函数也无法检索该文档。请指导我解决错误。

1 个答案:

答案 0 :(得分:0)

我认为问题出在您的cosmosdb中。

仅通过提供ID不可能获得指定的物品。容器中的同一ID中可以存在多个项目。

请看一下我的cosmosdb:

enter image description here

这是我的azure函数:

init .py:

import logging

import azure.functions as func


def main(req: func.HttpRequest, documents: func.DocumentList) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    if not documents:
        logging.warning("ToDo item not found")
    else:
        logging.info("Found ToDo item")
    return 'OK'

function.json:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "name": "documents",
      "type": "cosmosDB",
      "databaseName": "testbowman",
      "collectionName": "testbowman",
      "id" : "1",
      "partitionKey": "1",
      "connectionStringSetting": "MyAccount_COSMOSDB",
      "direction": "in"
  }
  ]
}

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "MyAccount_COSMOSDB":"AccountEndpoint=https://testbowman.documents.azure.com:443/;AccountKey=xxxxxx;"
  }
}

启动功能后,只有这样的物品可以被捕获:

{
    "id": "1",
    "testbowman": "1"
}

(这是因为我必须在提供ID的同时提供分区键的值。在我的情况下,分区键的名称是testbowman。)

实际使用它时,无需将值固定为1,可以通过{}指定相应参数的值。

您可以看到我可以成功到达这里:

enter image description here