Creating Bucket and Object Instances
The next step after creating your file is to see how to integrate it into your S3 workflow. This is where the resource’s classes play an important role, as these abstractions make it easy to work with S3. By using the resource, you have access to the high-level classes (Bucket
and Object
).
00:00
To upload that file that you just made, you’ll need to get it into Boto3 so that you can send it off to S3. This is where boto3.resource()
is very helpful, as it abstracts away a lot of the low-level stuff to make this happen.
00:13
resource()
gives you access to high-level classes like Bucket
and Object
, which you’ll use to identify the bucket and file that you want to work with.
00:21
Let’s open up a Python interpreter so you can see what this looks like. So first, import boto3
and make an s3_resource
from boto3.resource('s3')
.
00:37
I’ve saved the first bucket name from earlier, so I’m going to copy that and then make a new variable called first_bucket_name
and set that equal to that string.
00:52
To make a Boto3 bucket, you can just say something like first_bucket =
, call your s3_resource
,
01:02
and then make a Bucket
from there and set the name
equal to first_bucket_name
.
01:11
And just like that, first_bucket
is an s3.Bucket
through boto3
. Now let’s make a new string variable called first_file_name
, and set this equal to the filename from earlier.
01:30
Now if you want to make your first object, you can just say first_object = s3_resource
and then call .Object()
from there,
01:42
and this time pass in the bucket_name
, which is first_bucket_name
, and then the key
is going to equal first_file_name
.
02:00
If you look, that was created pretty quickly and no errors were generated even though we’ve associated this first_object
with this filename and the bucket. Obviously, we haven’t uploaded this file yet to S3, so this really can’t exist just yet.
02:17
The reason we don’t see any errors here is because these objects are only Python classes at this point, so no calls have been made to the AWS API. If you wanted to start pulling methods or attributes from this object, that’s when boto3
will start making API calls.
02:34
Another thing to note is that Bucket
and Object
are sub-resources of each other, meaning you can create an Object
while using a Bucket
, or return the Bucket
that an Object
is in from the Object
itself. Let’s take a look at how this works.
02:48
If you wanted to save first_object_again
, you can actually create this from the first_bucket
and call .Object()
from here and pass in that filename.
03:05
Likewise, if you wanted to get that Bucket
, you could say first_bucket_again
and set that equal to the first_object
and call .Bucket()
from there. And that’s all there is to it!
03:20 In the next video, you’ll actually upload this file to the bucket and learn how to download files from buckets. I’ll see you there.
Become a Member to join the conversation.