【问题标题】:DynamoDB table.get_item() get executed twiceDynamoDB table.get_item() 被执行两次
【发布时间】:2020-06-17 08:26:43
【问题描述】:

我正在为几个表创建 DAO 层。 由于有许多方法将在不同的 DAO 中使用,我想为所有这些方法使用父类并实现一些常用方法。我将table_name__name__ 属性传递给父类,以便它创建子类的记录器并创建正确的表变量。

下面是我的做法。

class Parent(object):    
    def __init__(self, class_name, table_name):
        ddb = boto3.resource("dynamodb", region_name=constants.AWS_REGION)
        self.table_name = table_name
        self.table = ddb.Table(table_name)
        self.logger = logging.getLogger(class_name)

    def get_record(self, **kwargs):
        try :
            self.logger.info(f"self type => {type(self)}")
            record = self.table.get_item(**kwargs)
            self.logger.info(f"record => {record}")
            record = record['Item']
            if record == {}:
                raise NoRecordException(f"No record with {kwargs} found in {self.table_name}")
        except botocore.exceptions.ClientError as e:
            raise e
        return record



class Child(Parent):

    def __init__(self, *args, **kwargs):
        super().__init__(self, class_name=__name__, table_name="Child")
        self.record = {}

    def get_child_record(self, id):
        return self.get_record(Key={"id": id})

当我调用Child().get_child_record(id) 时,我看到self.table.get_item 被执行了两次。不仅如此,它第二次使用record 本身而不是我调用该函数的 args 执行,结果低于错误。

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the GetItem operation: The provided key element does not match the schema 

我无法理解是什么触发了这种情况。我认为可能是因为 super() 所以我用父类名替换了它,但没有白费。

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: python-3.x amazon-dynamodb dynamodb-queries


    【解决方案1】:

    我给get_record() 打错电话了,这让我觉得事情正在重演。通过使用子对象和父对象调用方法进行测试时能够识别它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多