Last active
October 31, 2019 07:23
-
-
Save EngineerLabShimazu/59a0ffed55615051ca62247ed594233b to your computer and use it in GitHub Desktop.
Put json file to S3 from Lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import os | |
import boto3 | |
import botocore | |
def handler(event, context): | |
bucket = os.environ.get('BUCKET') | |
key = os.environ.get('KEY') | |
s3_resource = boto3.resource('s3') | |
obj = s3_resource.Object(bucket, key) | |
try: | |
current_json = json.loads(obj.get()['Body'].read().decode('utf-8')) | |
except botocore.exceptions.ClientError: | |
# file does not exist | |
updated_json = {'sample': 1} | |
else: | |
# file exist | |
if not isinstance(current_json['key'], int): | |
current_json['key'] = 0 | |
current_json['key'] = current_json['key'] + 1 | |
updated_json = current_json | |
r = obj.put(Body=json.dumps(updated_json)) | |
result = {'Body': obj.get()['Body'].read().decode('utf-8')} | |
return result |
これもできる!
from botocore.exceptions import ClientError
try:
response = s3.get_object(Bucket=bucket, Key=key)
except ClientError as ex:
if ex.response['Error']['Code'] == 'NoSuchKey':
logger.info('No object found - returning empty')
return dict()
else:
raise
https://stackoverflow.com/questions/42975609/how-to-capture-botocores-nosuchkey-exception
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
いいですね!