Skip to content

Instantly share code, notes, and snippets.

@afr-dt
Last active June 4, 2021 18:22
Show Gist options
  • Save afr-dt/32f3bb64a2acce66f940eb674d5b3629 to your computer and use it in GitHub Desktop.
Save afr-dt/32f3bb64a2acce66f940eb674d5b3629 to your computer and use it in GitHub Desktop.
Generate a presigned URL from S3 image
import boto3
import logging
from botocore.exceptions import ClientError
class S3Imgs:
def __init__(self, aws_access_key_id, aws_secret_access_key, region_name):
"""S3 secrests config.
Parameters
----------
aws_access_key_id : str
s3 key
aws_secret_access_key : str
s3 secret
region_name : str
s3 region
"""
self.s3 = boto3.client(
's3',
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=region_name
)
def create_presigned_url(self, bucket_name, object_name, expiration=3600):
"""Generate a presigned URL to share an S3 object
Parameters
----------
bucket_name : str
S3 bucket
object_name : str
img name
expiration : int, optional
time in seconds for the presigned URL to remain valid, by default 3600
Returns
-------
str
presigned URL as str, if error, returns None.
"""
try:
response = self.s3.generate_presigned_url(
'get_object',
Params={
'Bucket': bucket_name,
'Key': object_name
},
ExpiresIn=expiration
)
except ClientError as e:
logging.error(e)
return None
return response
# Use like this 👇
img = S3Imgs('S3_ACCESS_KEY', 'S3_SECRET_ACCESS_KEY', 'S3_REGION_NAME')
url = img.create_presigned_url('S3_BUCKET_NAME', 'S3_IMG_NAME')
print('IMG_URL', url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment