使用Azure函数应用程序和Python更新Azure表

2024-04-27 07:19:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从Azure函数更新Azure表中的现有行,但出现以下错误:

Functions.HttpTrigger1. Microsoft.Azure.WebJobs.Host: Error while handling parameter _binder after function returned:. Microsoft.Azure.WebJobs.Extensions.Storage: The specified entity already exists.

有些research seems表示需要指定一个ETag : '*',但我没有成功(我可能没有正确使用它)。有一个C# sample here(链接自引用的git问题)。一些进一步的研究似乎表明ETag值需要是头的一部分,但我无法确认这一点,如果这是真的,我也没有看到我可以在哪里/如何传递头

下面我使用“owner”作为行键,希望在新触发器上更新“val2Update”

Py代码

def main(req: func.HttpRequest, functionTableStorage: func.Out[str], messageJSON) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    
    owner = req.params.get('owner')
    val2Update = req.params.get('val')

    if owner:
        data = {
            "PartitionKey": "message",
            "RowKey": owner,
            "tester" : val2Update,
            "ETag": "*"
        } 
        functionTableStorage.set(json.dumps(data))
        
        return func.HttpResponse(f"Thanks, {owner}.")

绑定

{
  "type": "table",
  "direction": "out",
  "name": "functionTableStorage",
  "tableName": "masterTable",
  "connection": "AzureWebJobsStorage"
},

Tags: datagetfunctionparamsazurereqmicrosoftetag
1条回答
网友
1楼 · 发布于 2024-04-27 07:19:16

由于要使用函数App更新Azure表,因此不应使用输出绑定

如果我正确理解了您想要的内容,您应该将基本逻辑放在函数触发器的主体中,如下所示:(在调试之前,您应该首先运行以下命令:pip install azure-cosmosdb-table

import logging

import azure.functions as func
from azure.cosmosdb.table.tableservice import TableService
from azure.cosmosdb.table.models import Entity

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    table_service = TableService(connection_string='DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net')
    task = {'PartitionKey': 'tasksSeattle', 'RowKey': '001',
        'description': 'Take out the garbage', 'priority': 250}
    table_service.update_entity('tasktable', task)
    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello {name}!")
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )

这是我的原始实体:

enter image description here

这是更新后的实体:

enter image description here

这是官方文件:

https://docs.microsoft.com/en-us/azure/cosmos-db/table-storage-how-to-use-python?toc=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fstorage%2Ftables%2Ftoc.json&bc=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fbread%2Ftoc.json#update-an-entity

相关问题 更多 >