Skip to content

Instantly share code, notes, and snippets.

@rochacon
Last active May 25, 2016 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rochacon/447dccc03d83218cbb72 to your computer and use it in GitHub Desktop.
Save rochacon/447dccc03d83218cbb72 to your computer and use it in GitHub Desktop.
Simple script to upload a file to S3 using a pre-signed URL
#!/usr/bin/env python
# Reference: http://docs.aws.amazon.com/AmazonS3/latest/dev/PresignedUrlUploadObject.html
import argparse
import os
import boto
import requests
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Upload file to S3 using signed URL.')
parser.add_argument('filepath', help='File to be uploaded.')
parser.add_argument('bucket', help='Bucket name.')
parser.add_argument('key', help='Key to be used.')
parser.add_argument('--region', default='us-east-1', help='AWS bucket region.')
args = parser.parse_args()
s3 = boto.s3.connect_to_region(args.region)
content_length = os.stat(args.filepath).st_size
signed_url = s3.generate_url(30, 'PUT', args.bucket, args.key, headers={'Content-Length': str(content_length)})
print('Using URL "%s"' % signed_url)
with open(args.filepath) as fp:
requests.put(signed_url, data=fp, headers={'Content-Length': content_length})
key = s3.get_bucket(args.bucket).get_key(args.key)
print('Uploaded %s bytes to s3://%s/%s' % (key.size, args.bucket, args.key))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment