3 """A simple test API for accessing Windows Azure blob storage.
5 Parts of the code are modeled after boto (a library for accessing Amazon Web
6 Services), but this code is far less general and is meant only as a
9 import base64, hashlib, hmac, httplib, os, time
11 # The version of the Azure API we implement; sent in the x-ms-version header.
12 API_VERSION = '2009-09-19'
18 def add_auth_header(headers, method, path):
19 header_order = ['Content-Encoding', 'Content-Language', 'Content-Length',
20 'Content-MD5', 'Content-Type', 'Date', 'If-Modified-Since',
21 'If-Match', 'If-None-Match', 'If-Unmodified-Since',
24 if not headers.has_key('Date'):
25 headers['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT",
27 if not headers.has_key('x-ms-version'):
28 headers['x-ms-version'] = API_VERSION
30 StringToSign = method + "\n"
31 for h in header_order:
33 StringToSign += headers[h] + "\n"
37 # Add Canonicalized Headers
39 for (k, v) in headers.items():
41 if k.startswith('x-ms-'):
42 canonized.append((k, v))
44 for (k, v) in canonized:
45 StringToSign += "%s:%s\n" % (k, v)
47 # Add CanonicalizedHeaders Resource
48 account_name = os.environ['AZURE_ACCOUNT_NAME']
49 account_name = 'bluesky'
50 resource = "/" + account_name
54 (path, params) = path.split('?', 1)
55 params = [p.split('=') for p in params.split("&")]
56 params = dict((k.lower(), uri_decode(v)) for (k, v) in params)
58 for k in sorted(params):
59 resource += "\n%s:%s" % (k, params[k])
60 StringToSign += resource
62 # print "String to sign:", repr(StringToSign)
64 secret_key = os.environ['AZURE_SECRET_KEY']
65 secret_key = base64.b64decode(secret_key)
66 h = hmac.new(secret_key, digestmod=hashlib.sha256)
67 h.update(StringToSign)
69 signature = base64.b64encode(h.digest())
70 headers['Authorization'] = "SharedKey %s:%s" % (account_name, signature)
72 def generate_request(path, method='GET', body="", headers={}):
73 host = os.environ['AZURE_ACCOUNT_NAME'] + ".blob.core.windows.net"
74 #auth_path = conn.calling_format.build_auth_path(self.bucket, key)
76 headers = headers.copy()
77 headers['Content-Length'] = str(len(body))
79 headers['Content-MD5'] = base64.b64encode(hashlib.md5(body).digest())
80 add_auth_header(headers, method, path)
82 req = "%s %s HTTP/1.1\r\nHost: %s\r\n" % (method, path, host)
83 req = req + ''.join("%s: %s\r\n" % h for h in headers.items()) + "\r\n"
86 conn = httplib.HTTPConnection(host)
87 conn.request(method, path, body, headers)
88 response = conn.getresponse()
89 print "Response:", response.status
90 print "Headers:", response.getheaders()
91 print "Body:", response.read()
94 generate_request("/?comp=list")