Code


Version 4 (modified by anonymous, 7 years ago) (diff)

--

Here's a quick example of accessing Amazon Web Services using Python. You must first download and install Amara and obtain a Amazon Web Services access key.

from httplib import HTTPConnection 
from urlparse import urlparse, urlunparse 
import amara 
 
def paramunparse(params): 
    result = "" 
    for k, v in params.iteritems(): 
        result += k + "=" + v + "&" 
    return result.rstrip('&') 
 
AWSAccessKeyId = [Your Access Key ID Here] 
isbn = '0-3951-7711-1' 
# ISBN's are sometimes formatted with hyphens 
# The ASIN for books is equal to the ISBN with no hyphens 
asin = isbn.replace('-','')  
host = 'webservices.amazon.com' 
path = '/onca/xml' 
params = { 'Service': 'AWSECommerceService',  
           'AWSAccessKeyId': AWSAccessKeyId,  
           'Operation': 'ItemLookup',  
           'MerchantId': 'Featured', 
           'IdType': 'ASIN', 
           'ResponseGroup': 'Medium', 
           'ItemId': asin} 
 
query = urlunparse(('','',path, '', paramunparse(params), '')) 
print 'http://'+host+query 
conn = HTTPConnection(host) 
conn.request('GET',query) 
xmlresponse = conn.getresponse().read() 
doc = amara.parse(xmlresponse) 
print "Found", len(doc.ItemLookupResponse.Items.Item), "items." 
print "Looking at first item" 
item = doc.ItemLookupResponse.Items.Item[0] 
print "Title:", item.ItemAttributes.Title 
print "Authors:",  
for author in item.ItemAttributes.Author: 
    print author.__str__() + ";", 
 
print  
price = item.OfferSummary.LowestNewPrice.Amount #unformatted 
print "List Price:", item.ItemAttributes.ListPrice.FormattedPrice 
print "Amazon Price:", item.OfferSummary.LowestNewPrice.FormattedPrice 

Although this article is not directly related to Django, it will undoubtly be useful for many Django newbies.

You could also use boto instead of Amara.