Home > Blockchain >  How can I remove expiry from the S3 bucket image object URL?
How can I remove expiry from the S3 bucket image object URL?

Time:07-01

I am uploading multiple images to S3 bucket but once the images are attached and I receive the image URLs, they have certain expiry date. I don't want them to expire at all. What should I do?

Python code:

    from werkzeug.utils import secure_filename 
    url_attach = []
    image_file = request.files.getlist('files')
    for item in image_file:
        filename = secure_filename(item.filename)
        url = upload2s3(item, filename)
        url_attach.append(url)

upload function:

def upload2s3(img_content, key_name):
    try:
        s3_conn = boto3.client(
            "s3",
            aws_access_key_id=AWS_ACCESS_KEY_ID,
            aws_secret_access_key=AWS_SECRET_KEY,
        )
        x = s3_conn.put_object(Bucket=BUCKET_NAME, Body=img_content.read(), Key=key_name)
        url = create_url(BUCKET_NAME, key_name)
        return url
    except Exception as ex:
        return {"status": False, "message": ex}

url function:

def create_url(bucket, object):

    client = boto3.client(
        "s3", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_KEY
    )

    return client.generate_presigned_url(
        "get_object", Params={"Bucket": bucket, "Key": object}
    )

sample url: https://test_dir.s3.amazonaws.com/XYZ.png?AWSAccessKeyId=###########&Signature=##############&Expires=#########

Somewhere, I read that generate_presigned_url has max expiry as 7 days. is there any alternative to that?

CodePudding user response:

I don't want them to expire at all. What should I do?

Nothing, because its not possible. You have develop a custom solution to regenerate the new links when they about to expire. Otherwise do not use S3 Presigned URLs.Instead server your files through CloudFront.

  • Related