I have a method that fetches a file from a URL and converts it to OpenCV image
JavaScript
x
7
1
def my_method(self, imgurl):
2
req = urllib.urlopen(imgurl)
3
r = req.read()
4
arr = np.asarray(bytearray(r), dtype=np.uint8)
5
image = cv2.imdecode(arr,-1) # 'load it as it is'
6
return image
7
I would like to use boto3 to access an object from s3 bucket and convert it to an image just like above method does. However, I’m not sure how to access an item from a bucket using boto3 and then further how to read()
contents of that item.
Below is what I’ve tried
JavaScript
1
6
1
>>> import botocore
2
>>> import boto3
3
>>> client = boto3.client('s3',aws_access_key_id="myaccsskey",aws_secret_access_key="secretkey")
4
>>> bucketname = "mybucket"
5
>>> itemname = "demo.png"
6
Questions
- How can I access a particular item from a bucket using boto3?
- Is there a way to
read
the contents of the accessed item similar to what I’m doing inmy_method
usingreq.read()
?
Advertisement
Answer
I would do 1 this way:
JavaScript
1
9
1
import boto3
2
s3 = boto3.resource('s3',
3
use_ssl=False,
4
endpoint_url="http://localhost:4567",
5
aws_access_key_id="",
6
aws_secret_access_key="",
7
)
8
obj = s3.Object(bucketname, itemname)
9
For 2, I have never tried by this SO answer suggest:
JavaScript
1
2
1
body = obj.get()['Body'].read()
2
using the high-level ressource
proposed by boto3
.