使用Lambda更新文本文件

时间:2018-08-20 13:42:28

标签: python amazon-web-services amazon-s3 aws-lambda

每当我将图像上传到s3存储桶时,我都希望能够更新文本文件。该文本文件将在每一行上包含Amazon Rekognition的结果。但是,我编写的代码无法正常工作

bucket_name = "update-my-text-file"
rekognition = boto3.client('rekognition')
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket_name)

def handle_image(key):
    response = rekognition.detect_labels(
        Image={
            'S3Object': {
                'Bucket': bucket_name,
                'Name': key
            }
        }
    )
    return response


def lambda_handler(event, context):

    file_name = 'results.txt'
    object = s3.Object(bucket_name, 'tmp/results.txt')

    cli = boto3.client('s3')
    response = cli.get_object(Bucket=bucket_name, Key='tmp/results.txt')
    data = response['Body'].read()
    print('the data is ' + data)

    key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
    response = handle_image(key)
    print('the response is: ' + response)

    object.put(Body=data + '/n' + response)

1 个答案:

答案 0 :(得分:0)

您可能会发现这样下载文件更加容易:

import boto3
s3_client = boto3.client('s3')
s3_client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')

然后,您可以根据需要读取/写入本地文件。然后,再次上传:

s3_client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')