簡體   English   中英

使用 boto3 錯誤屬性名稱是保留關鍵字,有條件地將項目插入到 dynamodb 表中

[英]Conditionally insert an item into a dynamodb table using boto3 Error Attribute name is a reserved keyword

如果項目(狀態)不存在,我正在調用此函數來放置項目,我從這里指的東西: 如何使用 boto3 有條件地將項目插入到 dynamodb 表中..

    def put_items_if_doesnt_exist():
      dynamodb = boto3.resource('dynamodb',region_name='us-east-1')
      try:
          table = dynamodb.Table('awssolutions-ssm-hybrid-table')
          response = table.put_item(
          Item={
                  'name':'Execution',
                  'state': 'Locked',
              },
          ConditionExpression='attribute_not_exists(state) AND attribute_not_exists(name)'
          )
      except ClientError as e:
          # Ignore the ConditionalCheckFailedException
          if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
              raise

這里的問題是狀態是一個保留字,因此它失敗並顯示錯誤:

[ERROR] ClientError: An error occurred (ValidationException) when calling the PutItem operation: Invalid ConditionExpression: Attribute name is a reserved keyword; reserved keyword: state

有什么建議可以處理這個問題嗎?

這就是ExpressionAttributeNames用武之地,它們允許您使用保留名稱。 您只需添加一個帶有#前綴的占位符,並在ExpressionAttributeNames參數中指定其值。

    def put_items_if_doesnt_exist():
      dynamodb = boto3.resource('dynamodb',region_name='us-east-1')
      try:
          table = dynamodb.Table('awssolutions-ssm-hybrid-table')
          response = table.put_item(
          Item={
                  'name':'Execution',
                  'state': 'Locked',
              },
          ConditionExpression='attribute_not_exists(#state) AND attribute_not_exists(#name)',
          ExpressionAttributeNames={"#state": "state", "#name", "name"}
          )
      except ClientError as e:
          # Ignore the ConditionalCheckFailedException
          if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
              raise

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM