Skip to content

Instantly share code, notes, and snippets.

@utaal
Created January 17, 2012 21:49
Show Gist options
  • Save utaal/1629145 to your computer and use it in GitHub Desktop.
Save utaal/1629145 to your computer and use it in GitHub Desktop.
generate a s3 upload form
import json
import base64
import hmac, sha
import datetime
html = """
<html>
<head>
<title>Upload</title>
</head>
<body>
<form action="%(s3url)s" method="post" enctype="multipart/form-data">
<input type="hidden" name="AWSAccessKeyId" value="%(accesskeyid)s"></input>
<input type="hidden" name="acl" value="%(acl)s"></input>
<input type="hidden" name="key" value="%(key)s"></input>
<input type="hidden" name="policy" value="%(policy)s"></input>
<input type="hidden" name="redirect" value="%(redirect)s"></input>
<input type="hidden" name="signature" value="%(signature)s"></input>
<input type="file" name="file"></input>
<input type="submit" value="Upload"></input>
</form>
</body>
</html>"""
accesskeyid = "..."
secret = "..."
expiration = "2012-01-20T12:00:00.000Z"
bucket = "..."
key_prefix = base64.urlsafe_b64encode(hmac.new("...", datetime.datetime.now().strftime("%s"), sha).digest())
max_bytes = 500000000
acl = "private"
redirect = "http://" + bucket + ".s3.amazonaws.com/success.html"
policy_doc = {
"expiration": expiration,
"conditions": [
{"acl": acl},
{"bucket": bucket},
{"redirect": redirect},
["starts-with", "$key", key_prefix],
["content-length-range", 1, max_bytes]
]
}
policy_json = json.dumps(policy_doc)
policy = base64.b64encode(policy_json)
h = hmac.new(secret, policy, sha)
signature = base64.b64encode(h.digest())
html = html % {
"s3url": "http://" + bucket + ".s3.amazonaws.com/",
"accesskeyid": accesskeyid,
"acl": acl,
"key": key_prefix + "-${filename}",
"policy": policy,
"redirect": redirect,
"signature": signature
}
with open("upload-" + key_prefix + ".html", "w") as of:
of.write(html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment