首页 > 解决方案 > 使用 Python 更新 DynamoDB 中的项目的项目结构缺失

问题描述

我正在寻求帮助来解决我遇到的问题。

我正在使用 DynamoDB 和本文档来使用 Python 更新项目:

我想更新 2 个字段“状态”和“已解决”。

我原来的结构是这样的:incidents 是一个 List,里面是一个 Map,所以我只想更新 2 个值“status”和“resolved”

在此处输入图像描述

当我更新字段时,问题就来了,结构不一样,下一个是项目的结构 - 一个列表,在一个地图内,然后是一个地图:

在此处输入图像描述

我的代码是下一个:

import json
import json
import boto3
import random
from boto3.dynamodb.conditions import Key

def handle_modify(record):
    print("Handling MODIFY Event")
    print(record)

    incidences = record['dynamodb']['NewImage']['incidences']['L']
    print(record)
    dynamodb = boto3.resource('dynamodb', endpoint_url="https://dynamodb.eu-west-1.amazonaws.com")
    incidences2 = []
    for incidence in incidences:
        if incidence["M"]["type"]["S"] != "NO_RESPONSE_ON_TIME" and incidence["M"]["status"]["S"] == "RESOLVED":
            for incidence2 in incidences:
                incidence2["M"]["status"]["S"] = "RESOLVED"
                incidence2["M"]["resolved"]["BOOL"] = True
                incidences2.append(incidence2)

            break
    if len(incidences2) > 0:
        response = table.update_item(
            Key={
                'order_id': record['dynamodb']['NewImage']['order_id']['S']
            },
            UpdateExpression="set incidences=:incidences, last_status=:last_status, lastStatus=:lastStatus",
            ExpressionAttributeValues={
                ':incidences': incidences2
            },
            ReturnValues="UPDATED_NEW"
        )

def lambda_handler(event, context):
    try:
        for record in event['Records']:
            if record['eventName'] == 'MODIFY':
                handle_modify(record)
        return "Success!"
    except Exception as e: 
        print(e)
        return "Error"

你们能帮帮我吗?

我的观点是代码中的问题:


    for incidence in incidences:
        if incidence["M"]["type"]["S"] != "NO_RESPONSE_ON_TIME" and incidence["M"]["status"]["S"] == "RESOLVED":
            for incidence2 in incidences:
                incidence2["M"]["status"]["S"] = "RESOLVED"
                incidence2["M"]["resolved"]["BOOL"] = True
                incidences2.append(incidence2)

            break

谢谢!

标签: pythonpython-3.xamazon-web-servicesamazon-dynamodb

解决方案


尝试这个 :)

for incidence in incidences:
    if incidence["M"]["type"]["S"] != "NO_RESPONSE_ON_TIME" and incidence["M"]["status"]["S"] == "RESOLVED":
        incidence["M"]["type"]["S"] = "RESOLVED"

祝你好运


推荐阅读