Issue S3 time-limited URL with boto3 (with file existence confirmation)

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

Issue S3 time-limited URL with boto3 (with file existence confirmation)
Generate S3 signed URL with boto
[Python] Summary of S3 file operations with boto3
S3 uploader with boto
S3 operation with python boto3
Use boto3 to mess with S3
Download the file from S3 using boto.
Check the existence of the file with python
Issue a signed URL with AWS SQS
Try server-side encryption on S3 with boto3
[AWS] Link Lambda and S3 with boto3
S3 server-side encryption SSE with Python boto3
[AWS S3] Confirmation of the existence of folders on S3