Nicolas Raoul
Nicolas Raoul

Reputation: 60193

Writing string to S3 with boto3: "'dict' object has no attribute 'put'"

In an AWS lambda, I am using boto3 to put a string into an S3 file:

import boto3
s3 = boto3.client('s3')
data = s3.get_object(Bucket=XXX, Key=YYY)
data.put('Body', 'hello')

I am told this:

[ERROR] AttributeError: 'dict' object has no attribute 'put'

The same happens with data.put('hello') which is the method recommended by the top answers at How to write a file or data to an S3 object using boto3 and with data.put_object: 'dict' object has no attribute 'put_object'.

What am I doing wrong?

On the opposite, reading works great (with data.get('Body').read().decode('utf-8')).

Upvotes: 5

Views: 12090

Answers (1)

Nicolas Raoul
Nicolas Raoul

Reputation: 60193

put_object is a method of the s3 object, not the data object.

Here is a full working example with Python 3.7:

import json
import boto3
s3 = boto3.client('s3')
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):

    bucket = 'mybucket'
    key = 'id.txt'
    id = None

    # Write id to S3
    s3.put_object(Body='Hello!', Bucket=bucket, Key=key)

    # Read id from S3
    data = s3.get_object(Bucket=bucket, Key=key)
    id = data.get('Body').read().decode('utf-8') 
    logger.info("Id:" + id)


    return {
        'statusCode': 200,
        'body': json.dumps('Id:' + id)
    }

Upvotes: 11

Related Questions