我有一个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
我想我可以将其塞入对象并将其写出。有没有更好的方法可以做我想做的事?
答案 0 :(得分:0)
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Object.put
主体(字节或可搜索的类似文件的对象)-对象数据。
所以尝试像Body=json.dumps(response).encode()
您的response
是一个dict
对象