Download image from S3 bucket and store in a variable not in local (boto3)

Viewed 706

I want to download an image from a bucket S3 and store in a variable, not in my local pc, how can I do it?

I'm using this code to store in local:

BUCKET_NAME = 'mybucket' 
KEYFILE = 'myImage.jpg' 

try:
    s3.Bucket(BUCKET_NAME).download_file(KEYFILE, 'myImageInLocal.jpg')          
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
    else:
        raise
2 Answers

You can download to BytesIO variable with download_fileobj:

from io import BytesIO

BUCKET_NAME = 'mybucket' 
KEYFILE = 'myImage.jpg' 

s3_file = BytesIO()

try:
    s3.Bucket(BUCKET_NAME).download_fileobj('myImageInLocal.jpg', s3_file)          
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
    else:
        raise

May be you can try with BytesIO()

import io
image_data = io.BytesIO()

in your try block

s3.Bucket(BUCKET_NAME).download_file(KEYFILE, image_data)  

so image_data is the variable that should have the image in byte format.

Related