python - 无法从 Azure 事件中心写入 CosmosDB

标签 python azure azure-functions azure-cosmosdb azure-eventhub

我正在开发一个 Azure Function(2.x),它由来自事件中心的事件触发,并将接收到的数据写入 CosmosDB 实例。在部署它之前,我想在本地测试它并且读取事件可以完美地工作。但是,当我尝试写入 CosmosDB 时,出现此错误:

“System.Private.CoreLib:执行函数时出现异常:Functions.EventHubTrigger。Microsoft.Azure.DocumentDB.Core:消息:{“错误”:[“指定的输入之一无效”]}”

数据库实例是使用 Azure 门户创建的,我添加了几个虚拟条目,所有这些都运行良好。我做错了什么?

function.json:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "type": "eventHubTrigger",
      "name": "event",
      "direction": "in",
      "eventHubName": "event-hub-name",
      "connection": "event-hub-connection",
      "cardinality": "many",
      "consumerGroup": "$Default"
    },
    {
      "type": "cosmosDB",
      "direction": "out",
      "name": "doc",
      "databaseName": "database-name",
      "collectionName": "test",
      "createIfNotExists": "true",
      "connectionStringSetting": "CosmosDBConnectionString"
    }
  ]
}

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "storage-key",
    "CosmosDBConnectionString": "AccountEndpoint=document-db-endpoint;AccountKey=account-key;",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "event-hub-connection": "Endpoint=sb://endpoint-name;SharedAccessKeyName=shared-access-key-name;SharedAccessKey=shared-access-key" 
  }
}

host.json:

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  }
}

__init__.py:

import logging, json

import azure.functions as func


def main(event: func.EventHubEvent, doc: func.Out[func.Document]):

    event_data = event.get_body().decode("utf-8")
    logging.info('Python EventHub trigger processed an event: %s', event_data)

    # json object for testing the DB write operation
    temp = {}
    temp["id"] = 1
    temp["category"] = "feedback"
    temp = json.dumps(temp)

    doc.set(func.Document.from_json(temp))
    logging.info("CosmosDB updated!; Value: ", temp)

最佳答案

该错误是 HTTP 400,BadRequest。这意味着负载中的某些内容未正确形成 JSON,或者您的某些属性无效。

我看到你的 id 是一个数字,但在 REST 合约中,它是一个字符串。引用:https://learn.microsoft.com/rest/api/cosmos-db/create-a-document#body

你能把id改成字符串吗?

关于python - 无法从 Azure 事件中心写入 CosmosDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60302169/

相关文章:

python - URL 处出现 NoReverseMatch 错误,X 未注册命名空间

python - 带有 SubFactory 字段的 DjangoModelFactory 不创建新条目而是指向现有条目

linq - 从 "LINQ to SQL"到 "Azure Table Storage"或 "SQL Data Service"

azure - 如何使用 Azure CLI 将 Azure 虚拟机加入 AD 域

powershell - 将资源从事件目录移动到同一订阅中的另一个事件目录

azure - 当服务计划位于不同的资源组中时如何部署 Azure Functions 应用程序

python - 为什么此代码会导致 Excel 中出现按字母顺序排列的列列表?

python - 使用另一列中的值对 str.starts_with() 进行极坐标分析

c# - 如何通过 Visual Studio 在本地将 https 与 Azure Functions 结合使用?

c# - 在 Azure Function V4 中配置 Azure KeyVault 端点