Skip to content

Instantly share code, notes, and snippets.

@gmirsky
Created March 20, 2023 19:46
Show Gist options
  • Save gmirsky/bc640b9053e0b9bad9b3451ea69e4b0f to your computer and use it in GitHub Desktop.
Save gmirsky/bc640b9053e0b9bad9b3451ea69e4b0f to your computer and use it in GitHub Desktop.
Python generate pre-signed URL
import sys as sys
import logging as logging
import platform as platform
import boto3 as boto3
import argparse as argparse
import requests as requests
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
def generate_presigned_url(s3_client, client_method, method_parameters, expires_in):
"""
Generate a presigned Amazon S3 URL that can be used to perform an action.
:param s3_client: A Boto3 Amazon S3 client.
:param client_method: The name of the client method that the URL performs.
:param method_parameters: The parameters of the specified client method.
:param expires_in: The number of seconds the presigned URL is valid for.
:return: The presigned URL.
"""
logging.basicConfig(level=logging.INFO,
format='%(levelname)s: %(message)s')
try:
url = s3_client.generate_presigned_url(
ClientMethod=client_method,
Params=method_parameters,
ExpiresIn=expires_in
)
logger.info("Got presigned URL: %s", url)
except ClientError:
logger.exception(
"Couldn't get a presigned URL for client method '%s'.", client_method)
raise
return url
def main():
''' main function '''
logging.basicConfig(level=logging.INFO,
format='%(levelname)s: %(message)s')
print('-' * 72)
print("Platform: {}".format(platform.platform()))
print("Python version: {}".format(sys.version))
print('-' * 72)
if sys.version_info[0] < 3:
raise Exception("You must use Python 3 or higher")
parser = argparse.ArgumentParser()
parser.add_argument('--region', help='AWS region', default='us-east-1')
parser.add_argument('--profile', help='AWS profile', default='default')
parser.add_argument('--bucket', help="The name of the bucket.")
parser.add_argument(
'--key', help="For a GET operation, the key of the object in Amazon S3. For a "
"PUT operation, the name of a file to upload.")
parser.add_argument(
'--action', choices=('get', 'put'), help="The action to perform.", default='get')
args = parser.parse_args()
print("Region: {}".format(args.region))
print("Profile: {}".format(args.profile))
print("Key: {}".format(args.key))
print("Action: {}".format(args.action))
region = args.region
profile = args.profile
session = boto3.Session(profile_name=profile, region_name=region)
client_action = 'get_object' if args.action == 'get' else 'put_object'
s3_client = session.client('s3', use_ssl=True, verify=True)
url = generate_presigned_url(
s3_client, client_action, {'Bucket': args.bucket, 'Key': args.key}, 1000)
print('-' * 72)
print("Presigned URL: {}".format(url))
print('-' * 72)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment