Skip to content

Instantly share code, notes, and snippets.

@chrisseto
Created February 13, 2014 23:40
Show Gist options
  • Save chrisseto/8986330 to your computer and use it in GitHub Desktop.
Save chrisseto/8986330 to your computer and use it in GitHub Desktop.
How to generate an s3 signed url in python
def generate_signed_url(mime, file_name, s3):
"""
:param mime str: The file mime type.
:param file_name str: The name of the file to be upload into s3.
:param s3 Object: An object containing the bucket name and access keys to amazon.
:return str: The signed url.
"""
expires = int(time.time() + 10)
amz_headers = 'x-amz-acl:private'
request_to_sign = str("PUT\n\n{mime_type}\n{expires}\n{amz_headers}\n/{resource}".format(
mime_type=mime, expires=expires, amz_headers=amz_headers, resource=s3.bucket + '/' + file_name))
url = 'https://s3.amazonaws.com/{bucket}/{filename}'.format(
filename=file_name, bucket=s3.bucket)
signed = urllib.quote_plus(base64.encodestring(
hmac.new(str(s3.secret_key), request_to_sign, sha).digest()).strip())
return '{url}?AWSAccessKeyId={access_key}&Expires={expires}&Signature={signed}'.format(url=url, access_key=s3.access_key, expires=expires, signed=signed),
#/blackhttpmagick
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment