-
-
Save afaheem88/1d16638c7653280bca40 to your computer and use it in GitHub Desktop.
A small python code to create formpost object in swift/ceph. This is a basic demonstration of form-post and does not have error handlings. Use it at your own risk.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
import hmac | |
import time | |
import urlparse | |
import sys | |
import httplib2 | |
class ObjectFormPost(): | |
def __init__(self): | |
self.base_url = sys.argv[1] | |
self.container_name = sys.argv[2] | |
self.object_name = sys.argv[3] | |
self.key = sys.argv[4] | |
self.auth_key = sys.argv[5] | |
def get_multipart_form(self, expires=600): | |
path = "%s/%s/%s" % ( | |
urlparse.urlparse(self.base_url).path, | |
self.container_name, | |
self.object_name) | |
redirect = '' | |
max_file_size = 104857600 | |
max_file_count = 10 | |
expires += int(time.time()) | |
hmac_body = '%s\n%s\n%s\n%s\n%s' % (path, | |
redirect, | |
max_file_size, | |
max_file_count, | |
expires) | |
signature = hmac.new(self.key, hmac_body, hashlib.sha1).hexdigest() | |
fields = {'redirect': redirect, | |
'max_file_size': str(max_file_size), | |
'max_file_count': str(max_file_count), | |
'expires': str(expires), | |
'signature': signature} | |
boundary = '--boundary--' | |
data = [] | |
for (key, value) in fields.items(): | |
data.append('--' + boundary) | |
data.append('Content-Disposition: form-data; name="%s"' % key) | |
data.append('') | |
data.append(value) | |
data.append('--' + boundary) | |
data.append('Content-Disposition: form-data; ' | |
'name="file1"; filename="testfile"') | |
data.append('Content-Type: application/octet-stream') | |
data.append('') | |
data.append('hello world') | |
data.append('--' + boundary + '--') | |
data.append('') | |
body = '\r\n'.join(data) | |
content_type = 'multipart/form-data; boundary=%s' % boundary | |
return body, content_type | |
def post_object_using_form(self): | |
body, content_type = self.get_multipart_form() | |
headers = {'Content-Type': content_type, | |
'Content-Length': str(len(body)), | |
'x-auth-token': self.auth_key} | |
url = "%s/%s/%s" % (self.base_url, self.container_name, self.object_name) | |
http = httplib2.Http() | |
print http.request(url,"POST", body=body, headers=headers) | |
def main(): | |
if len(sys.argv) < 6: | |
print "Usage: command base_url container object temp-url-key auth-key" | |
exit(1) | |
obj = ObjectFormPost() | |
obj.post_object_using_form() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment