views:

18

answers:

0

Here's the code:

import urllib2
import base64,hashlib,hmac,time
from urllib import urlencode
from xml.dom import minidom

AWS_ACCESS_KEY_ID = "secret"
AWS_SECRET_ACCESS_KEY = "secret"

base_url = "http://ecs.amazonaws.com/onca/xml"
url_params = {"Version": "2010-09-01",
              "Operation": "ItemSearch",
              "ResponseGroup": "Images",
              "SearchIndex": "Books",
              "Keywords": "Python",
              "AWSAccessKeyId": AWS_ACCESS_KEY_ID,
              "Service": "AWSCommerceService"
             }


# Add a ISO 8601 compliant timestamp (in GMT)
url_params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())

# Sort the URL parameters by key
keys = url_params.keys()
keys.sort()
# Get the values in the same order of the sorted keys
values = map(url_params.get, keys)

# Reconstruct the URL paramters and encode them
url_string = urlencode(zip(keys,values))
url_string = url_string.replace('+',"%20")
url_string = url_string.replace(':',"%3A")

#Construct the string to sign
string_to_sign = """GET
ecs.amazonaws.com
/onca/xml
%s""" % url_string

# Sign the request
signature = hmac.new(
            key=AWS_SECRET_ACCESS_KEY,
            msg=string_to_sign,
            digestmod=hashlib.sha256).digest()

# Base64 encode the signature
signature = base64.encodestring(signature)

# Make the signature URL safe
signature = signature.replace('+','%20')
signature = signature.replace('=','%3D')
signature = signature.replace(':','%3A')
url_string += "&Signature=%s" % signature

print "%s?%s" % (base_url,url_string)

When used with Django, i constantly get a 403 Forbidden error. When used without Django it sometimes works and sometimes doesn't. I have no idea what the cause of this might be.