亚马逊 API 签名请求无法正常工作

1 投票
1 回答
976 浏览
提问于 2025-04-16 05:58

这是代码:

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禁止访问的错误。而在不使用Django的时候,有时能正常工作,有时又不行。我完全不知道这可能是什么原因。

1 个回答

2

Adam Cox 曾经在他的博客上分享了一个很不错的例子,讲的是如何给请求的 URL 签名: 页面未找到

当然,你也可以选择简单点,直接使用 python-amazon-product-api 这个库。

如果你需要在 Google App Engine 上使用它,可以看看这个讨论串:在 Google App Engine 上使用 python-amazon-product-api 而不使用 lxml

撰写回答