2010-10-23 161 views
1

下面的代碼:亞馬遜API簽署的請求不能正常工作

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) 

當Django的使用,我不斷收到403 Forbidden錯誤。在沒有Django的情況下使用它有時會起作用,有時不起作用。我不知道這可能是什麼原因。

+0

它支持的產品廣告API? – user216171 2010-10-23 16:17:54

回答