【发布时间】:2019-11-17 07:42:58
【问题描述】:
我正在构建一个 Python 3.6 AWS Lambda 函数来查询 Cost Explorer 和其他一些服务。我想将返回的字符串响应写入一个 JSON 对象,我可以上传到 S3 或 DynamoDB。
函数的工作示例如下
import boto3
def handler(event,context):
client = boto3.client('ce')
response = client.get_cost_forecast(
TimePeriod={
'Start': '2019-06-01', ## Start must be one day after creation date of function
'End': '2020-07-01'
},
Metric='UNBLENDED_COST',
Granularity='MONTHLY',
PredictionIntervalLevel=90 ## 51 - 99 Range
)
return str (response)
在控制台中返回就好了,现在我尝试将响应放入我想写入 S3 的对象的正文中
import boto3
def handler(event,context):
client = boto3.client('ce')
s3 = boto3.resource('s3')
object = s3.Object('my-bucket', 'my/path/object.json')
response = client.get_cost_forecast(
---ce python stuff---
object.put(Body=response)
return str (response)
这没有按预期工作,我从 CloudWatch 收到此错误
Parameter validation failed:
Invalid type for parameter Body, value: {'Total': {'Amount': '...RESPONSE...'}, 'RetryAttempts': 0}}, type: <class 'dict'>, valid types: <class 'bytes'>, <class 'bytearray'>, file-like object: ParamValidationError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 17, in handler
object.put(Body=response)
File "/var/task/boto3/resources/factory.py", line 520, in do_action
response = action(self, *args, **kwargs)
File "/var/task/boto3/resources/action.py", line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params)
File "/var/task/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/var/task/botocore/client.py", line 634, in _make_api_call
api_params, operation_model, context=request_context)
File "/var/task/botocore/client.py", line 682, in _convert_to_request_dict
api_params, operation_model)
File "/var/task/botocore/validate.py", line 297, in serialize_to_request
raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Body, value: {'Total': {'Amount': '...RESPONSE...'}, 'RetryAttempts': 0}}, type: <class 'dict'>, valid types: <class 'bytes'>, <class 'bytearray'>, file-like object
我想我可以把它塞进对象里然后写出来。有没有更好的方法来做我想做的事情?
【问题讨论】:
标签: python json amazon-s3 aws-lambda boto3