I have following model
class MediaFile(Media):
s3_file = GenericFileField(tag="s3-tag", null=True, blank=True, max_length=300)
How can I get size of file stored on s3?
I tried this, but it's not work.
def file_size(self):
try:
prefix = get_file_key(self.s3_file)
s3 = boto3.resource("s3")
bucket = s3.Bucket()
return bucket.Object(prefix).content_length
except:
pass
CodePudding user response:
To access an existing Bucket using boto3, you need to supply the bucket name, for example:
import boto3
s3 = boto3.resource("s3")
bucket = s3.Bucket('mybucket')
length = bucket.Object('cats/persian.jpg').content_length
Alternatively:
import boto3
s3 = boto3.resource("s3")
length = s3.Object('mybucket', 'cats/persian.jpg').content_length
FYI the value passed to Bucket.Object()
is a key (like cats/persian.jpg
), not a prefix (like cats/
).