如何格式化DynamoDB Scan()API(Python)的响应

2024-10-04 07:35:37 发布

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

我正在做一个API网关练习,我一直在格式化来自DynamoDB的响应。以下是我得到的答复:

{'Items': [{'Date': Decimal('3022020'), 'ResultID': Decimal('32'), 'Team': 'Roma', 'League': 'SerieA', 'Result': '3-1'}, {'Date': Decimal('3022020'), 'ResultID': Decimal('31'), 'Team': 'Roma', 'League': 'SerieA', 'Result': '3-1'}, {'Date': Decimal('3022020'), 'ResultID': Decimal('29'), 'Team': 'Roma', 'League': 'SerieA', 'Result': '3-1'}, {'Date': Decimal('3022020'), 'ResultID': Decimal('30'), 'Team': 'Roma', 'League': 'SerieA', 'Result': '3-1'}], 'Count': 4, 'ScannedCount': 11, 'ResponseMetadata': {'RequestId': 'MP2RQ0V4QT898T10DVMMJVMMVRVV4KQNSO5AEMVJF66Q9ASUAAJG', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Sun, 06 Dec 2020 18:29:46 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '487', 'connection': 'keep-alive', 'x-amzn-requestid': 'MP2RQ0V4QT898T10DVMMJVMMVRVV4KQNSO5AEMVJF66Q9ASUAAJG', 'x-amz-crc32': '972061714'}, 'RetryAttempts': 0}}

对我来说,它看起来像一个嵌套数组,但每当我尝试使用响应对象时,它都会抛出内部服务器错误。本质上,lambda正在扫描数据库中的两个属性(联赛和球队),并将结果作为响应以强制字符串的形式返回给浏览器。下面是我处理未格式化字符串对象的要点

dbresponse = table.scan(FilterExpression=....)

responseObject = {
    'statusCode': 200
    'body': str(dbresponse)
}

return responseObject

我想用'body':str(dbresponse)格式的东西作为来自DynamoDB的响应,但我真的不知道该怎么做

谢谢

编辑

所以我似乎还没有像我想象的那样真正掌握“助手方法”的概念(见下面的答案)

我在lambda_处理程序默认方法中添加了helper方法的非工作版本。我得到了一些NameErrors,我假设我传入了错误的对象,或者调用了数组中的属性或者其他错误的东西

def json_response(respDB):
        for response in respDB['Items']:
            response = response + { Date: respDB.Date, 
            League: respDB.League, Team: respDB.Team, 
            Score: respDB.Score }
            
        return response

另外,正如建议的那样,我正在使用这个方法,并按照建议将数据库响应变量作为'body': json_response(respDB)传入

谢谢你的帮助


Tags: 对象方法jsondateresponse错误resultteam
1条回答
网友
1楼 · 发布于 2024-10-04 07:35:37

您需要自己用JSON构建响应主体。尝试创建一个helper方法,该方法接收DynamoDB的输出并输出格式化的JSON

helper方法应如下所示:

def json_response(respDB):
  response = []
  for item in respDB['Items']:
    response.append( { 'Date': item['Date'], 'League': item['League'], 'Team': item['Team']})
            
  return response

并使用它来构建一个格式正确的响应体

dbresponse = table.scan(FilterExpression=....)
responseObject = {
    'statusCode': 200
    'body': format_response(dbresponse)
}

return responseObject

相关问题 更多 >