Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Python boto3 store file in S3 bucket

ok, I've seen a few examples of this, and here is my code in AWS Lambda Python 3.6:

# I just wrote out the file before this...
import boto3
tmp = open('/tmp/' + name_str,"rb") 
s3_client = boto3.resource('s3')
bucket = s3_client.Bucket(S3BUCKETNAME)
bucket.put_object(Key=name_str, Body=tmp, ContentType='text/csv', ContentEncoding='utf-8')

The error I get is :

's3.ServiceResource' object has no attribute 'put_object': AttributeError

Well, then I try:

s3_client.upload_file('/tmp/' + name_str, S3BUCKETNAME, name_str)

's3.ServiceResource' object has no attribute 'upload_file': AttributeError

So... I must be missing something basic... Is there some other import? Why can't the system find these functions?

like image 603
Robert Achmann Avatar asked Nov 16 '17 12:11

Robert Achmann


People also ask

Can Lambda upload file to S3?

AWS LAMBDA- Serverless Computing Amazon S3 service is used for file storage, where you can upload or remove files. We can trigger AWS Lambda on S3 when there are any file uploads in S3 buckets. AWS Lambda has a handler function which acts as a start point for AWS Lambda function.


1 Answers

This was a misunderstanding of what type to use. It should have been:

s3_client = boto3.client('s3')

But note that the code I actually use now is more like:

s3_client = boto3.client('s3')
with open('/tmp/' + name_str) as file:
    object = file.read()
    s3_client.put_object(Body=object, Bucket=S3BUCKET, Key=name_str, ContentType='whatever/something', ContentEncoding='whatever-itis', StorageClass='PICK_ONE', ACL='you_choose')
like image 125
Robert Achmann Avatar answered Oct 15 '22 00:10

Robert Achmann