Sunday 22 September 2019

AWS S3 upload files | Upload file to S3 using python | Lambda upload files to S3 bucket

S3 is storage provided by AWS. It stores data inside buckets.
We can upload data to s3 using boto3 library. Here is code which also works for AWS lambda functions.

Below is sample code to upload files to S3 using python :

import json
import boto3 
import requests

access_key='your_access_key'
secret_access='your_secret_access'
region = 'your_region'
s3 = boto3.resource('s3', region_name=region, aws_access_key_id=access_key,
                                   aws_secret_access_key=secret_access)
  
def s3_uplaod(bucket, domain,content):
    file_path = '{}/{}'.format(domain,"name_of_file")
    object = s3.Object(bucket, file_path)
    object.put(Body=content)

def main(job):
    try:
        bucket = 'your_bucket_name'
        domain = 'sub-folder_inside_bucket'
        content = 'local_location_of_file'
        s3_uplaod(bucket, domain,content)
    except Exception as e:
        print(e)

def handler(event, context):
    main(event)
handler('a','a')

Notes:

  1. You can replace required parameters like keys and bucket name.
  2. domain : used where we have folder inside bucket.
  3. if path doesn't exist inside bucket it will create required path.
  4. You can skip handler part if not using code for AWS lambda functions.
You can comment below if you face any issues here.


5 comments: