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.

Revisions

  1. afr-dt renamed this gist Jun 4, 2021. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. afr-dt revised this gist Jun 4, 2021. No changes.
  3. afr-dt revised this gist Jun 4, 2021. 1 changed file with 9 additions and 1 deletion.
    10 changes: 9 additions & 1 deletion s3_presigned_url.py
    Original file line number Diff line number Diff line change
    @@ -55,4 +55,12 @@ def create_presigned_url(self, bucket_name, object_name, expiration=3600):
    except ClientError as e:
    logging.error(e)
    return None
    return response
    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)
  4. afr-dt created this gist Jun 3, 2021.
    58 changes: 58 additions & 0 deletions s3_presigned_url.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    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