首页 > 解决方案 > 如何从 DynamoDB 中获取项目并存储元素以将其用于 Pytest?

问题描述

如何从 DynamoDB 中获取项目并在 Pytest 中使用环境(元素)?我的函数使用 boto3 来获取环境,并将环境存储在一个名为env[].

def get_environment():
    """
    Retrieves environment from DynamoDB
    :param ssm_client:
    :return:
    """
    env = []
    try:
        response = dynamodb_client.scan(
            TableName='accounts',
            AttributesToGet=['account_id','environment'],
            )
        env =  [ s['environment'] for s in response['Items'] ]
        return env
    except Exception as e:
        print("[ERROR] Failed")

回复:

[{'environment': {'S': 'sandbox'}, 'account_id': {'S': '409XX'}}, {'environment': {'S': 'services'}, 'account_id': {'S': '3228XX'}}, {'environment': {'S': 'non-production'}, 'account_id': {'S': '1145XX'}}, {'environment': {'S': 'production'}, 'account_id': {'S': '37988XX'}}, {'environment': {'S': 'non-production'}, 'account_id': {'S': '38856XXX'}}, {'environment': {'S': 'non-production'}, 'account_id': {'S': '10819XXXX'}}]

当我尝试打印环境名称时,它会引发错误

def print_environment():
    response = get_environment()
    environment =  [ item['environment'] for item in response ]
    print(environment)

  File "app.py", line 250, in print_environment
    environment =  [ item['environment'] for item in response ]
  File "app.py", line 250, in <listcomp>
    environment =  [ item['environment'] for item in response ]
KeyError: 'environment'

我只想为特定的 accountID 获取 Environment 并将其存储environment并在 pytest 中使用它。例子

 def test_environment():
    environment = get_environment()
    account_id = get_account_ids()
    for accounts in account_id:     
        if (environment = 'production') then assert something .....

标签: pythonamazon-web-servicesamazon-dynamodbpytestboto3

解决方案


您的字典列表不包含“环境”作为键。

它包含“环境”指向的值。

这种值的示例是{'S': 'sandbox'}, 'account_id': {'S': '409XX'}}


推荐阅读