You can issue a time-limited URL with generate_presigned_url
, but there is a problem that you can also create a key for which the object does not exist.
So I tried to issue a time-limited URL after checking if the object actually exists with get_object.
import boto3
import botocore
import logging
logger = logging.getLogger()
def create_presigned_url( bucket_name, key ):
s3 = boto3.client('s3')
try:
s3.get_object(
Bucket = bucket_name,
Key = key
)
url = s3.generate_presigned_url(
ClientMethod = 'get_object',
Params = {
Bucket = bucket_name,
Key = key
},
ExpiresIn = 3600,
HttpMethod = 'GET'
)
return url
except botocore.exceptions.ClientError as e:
logger.warning(e)
return 'File ' + bucket_name + '/' + key + 'not found'
bucket_name = 'BUCKET_NAME'
key = 'S3_OBJECT_KEY'
create_presigned_url( bucket_name, key )
If you run get_object on an object that doesn't exist, you'll get a ClientError
.
So, if the object does not exist with try ~ except
using it, the process is terminated without executing generate_presigned_url.
Recommended Posts