Rev 12440 | Rev 12597 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
from xml.dom.minidom import parseStringimport reimport urllibimport hashlibimport hmacimport base64from time import strftime, gmtimefrom requests import requestfrom operator import itemgetterclass MWS(object):URI = "/"VERSION = "2009-01-01"NS = ''def __init__(self, access_key, secret_key, merchant_id,domain='https://mws-eu.amazonservices.com', uri="", version=""):self.access_key = access_keyself.secret_key = secret_keyself.merchant_id = merchant_idself.domain = domainself.uri = uri or self.URIself.version = version or self.VERSIONdef make_request(self, extra_data, action,method="GET", **kwargs):params = {'AWSAccessKeyId': self.access_key,'SignatureVersion': '2','Timestamp': self.get_timestamp(),'Version': self.version,'SignatureMethod': 'HmacSHA256','Action': action}if action=='GetLowestOfferListingsForSKU':params['ExcludeMe']='true'params.update(extra_data)request_description = '&'.join(['%s=%s' % (k, urllib.quote(params[k], safe='-_.~').encode('utf-8')) for k in sorted(params)])signature = self.calc_signature(method, request_description)url = '%s%s?%s&Signature=%s' % (self.domain, self.uri, request_description, urllib.quote(signature))headers = {'User-Agent': 'AmazonJavascriptScratchpad/1.0 (Language=Python)'}headers.update(kwargs.get('extra_headers', {}))response = request(method, url)if action=='GetLowestOfferListingsForSKU':return self.parse_competitor_pricing_response(response)elif action=='GetMyPriceForSKU':return self.parse_my_pricing_response(response)else:raisedef parse_competitor_pricing_response(self,response):spString = re.sub('<\?.*\?>','',response.text)spString = "<dom>" + spString + "</dom>"dom = parseString(spString)skuOffers = dom.getElementsByTagName('GetLowestOfferListingsForSKUResult')offerMap = {}for skuOffer in skuOffers:status = skuOffer.attributes.items()[0][1]sku = skuOffer.attributes.items()[1][1]info = []for offer in skuOffer.getElementsByTagName('LowestOfferListing'):temp = {}try:if len(info)==3:breakamount = offer.getElementsByTagName('Amount')[0].firstChild.nodeValuetemp['sellingPrice'] = float(amount)temp['promoPrice'] = float(amount)temp['fulfillmentChannel'] = offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValuetry:temp['shippingTime'] = (offer.getElementsByTagName('Max')[0].firstChild.nodeValue).replace('days','')except:temp['shippingTime'] = '0-0'try:temp['rating'] = (offer.getElementsByTagName('SellerPositiveFeedbackRating')[0].firstChild.nodeValue)if temp['rating'] == 'Just Launched':temp['rating'] = '0'else:str_rating = temp['rating'].replace('-',' ').replace('%','')a = str_rating.split()l = []for x in a:if x.isdigit():l.append(x)temp['rating'] = l[0]except:temp['rating'] = '0'except:passtemp['notOurSku'] = Trueinfo.append(temp)offerMap[sku]=inforeturn offerMapdef parse_my_pricing_response(self,response):spString = re.sub('<\?.*\?>','',response.text)spString = "<dom>" + spString + "</dom>"dom = parseString(spString)skuOffers = dom.getElementsByTagName('GetMyPriceForSKUResult')skuMap = {}for skuOffer in skuOffers:try:status = skuOffer.attributes.items()[0][1]sku = skuOffer.attributes.items()[1][1]asin = skuOffer.getElementsByTagName('ASIN')[0].firstChild.nodeValueexcept:continuefor offer in skuOffer.getElementsByTagName('Offers'):temp = {}try:promoPrice = offer.getElementsByTagName('LandedPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValueregularPrice = offer.getElementsByTagName('RegularPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValuetemp['sellingPrice'] = float(regularPrice)temp['promoPrice'] = float(promoPrice)if promoPrice == regularPrice:temp['promotion'] = Falseelse:temp['promotion'] = Truetemp['status'] = statustemp['asin'] = asintemp['notOurSku'] = Falsetemp['fulfillmentChannel'] ='AMAZON'temp['shippingTime'] = '0-0'temp['rating'] = '0'except:passskuMap[sku]=tempreturn skuMapdef calc_signature(self, method, request_description):sig_data = method + '\n' + self.domain.replace('https://', '').lower() + '\n' + self.uri + '\n' + request_descriptionreturn base64.b64encode(hmac.new(str(self.secret_key), sig_data, hashlib.sha256).digest())def get_timestamp(self):return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())class Products(MWS):URI = '/Products/2011-10-01'VERSION = '2011-10-01'NS = '{https://mws-eu.amazonservices.com/Products/2011-10-01}'def get_my_pricing_for_sku(self, marketplaceid, skus):data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)num=0for sku in skus:data['SellerSKUList.SellerSKU.%d' % (num + 1)] = skunum+=1return self.make_request(data,'GetMyPriceForSKU')def get_competitive_pricing_for_sku(self, marketplaceid, skus):data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)num=0for sku in skus:data['SellerSKUList.SellerSKU.%d' % (num + 1)] = skunum+=1return self.make_request(data,'GetLowestOfferListingsForSKU')def main():p = Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")comp = p.get_competitive_pricing_for_sku('A21TJRUUN4KGV', ['FBA16293'])our = p.get_my_pricing_for_sku('A21TJRUUN4KGV', ['FBA3024'])print compprint our#print our.get('promotion')# print comp.get('FBA12248')# print our.get('FBA12248')# x = (our.get('FBA12248'))# x['sellingPrice']=41089# l = (comp.get('FBA12248'))# l.append((our.get('FBA12248')))# print sorted(l, key=itemgetter('promoPrice','notOurSku'))if __name__=='__main__':main()