Subversion Repositories SmartDukaan

Rev

Rev 12430 | Rev 12436 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

from xml.dom.minidom import parseString
import re
import urllib
import hashlib
import hmac
import base64
from time import strftime, gmtime
from requests import request
from operator import itemgetter


class 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_key
        self.secret_key = secret_key
        self.merchant_id = merchant_id
        self.domain = domain
        self.uri = uri or self.URI
        self.version = version or self.VERSION

    def 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:
            raise
    
    def 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'):
                if len(info)==3:
                    break
                temp = {}
                amount = offer.getElementsByTagName('Amount')[0].firstChild.nodeValue
                temp['sellingPrice'] = amount
                temp['promoPrice'] = amount
                temp['fulfillmentChannel'] = offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValue
                try:
                    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'
                temp['notOurSku'] = True
                info.append(temp)
            offerMap[sku]=info        
        return offerMap
    
    def 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:
            status = skuOffer.attributes.items()[0][1]
            sku = skuOffer.attributes.items()[1][1]
            asin = skuOffer.getElementsByTagName('ASIN')[0].firstChild.nodeValue
            print "fetching details of ",sku
            for offer in skuOffer.getElementsByTagName('Offers'):
                temp = {}
                promoPrice = offer.getElementsByTagName('LandedPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
                regularPrice = offer.getElementsByTagName('RegularPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
                temp['sellingPrice'] = regularPrice
                temp['promoPrice'] = promoPrice
                if promoPrice == regularPrice:
                    temp['promotion'] = False
                else:
                    temp['promotion'] = True
                temp['status'] = status
                temp['asin'] = asin
                temp['notOurSku'] = False
                temp['fulfillmentChannel'] ='AMAZON'
                temp['shippingTime'] =  '0-0'
                temp['rating'] = '0'
            skuMap[sku]=temp     
        return skuMap    
        
        
    def calc_signature(self, method, request_description):
        sig_data = method + '\n' + self.domain.replace('https://', '').lower() + '\n' + self.uri + '\n' + request_description
        return 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=0
        for sku in skus:
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
            num+=1
        return self.make_request(data,'GetMyPriceForSKU')
    

    def get_competitive_pricing_for_sku(self, marketplaceid, skus):
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
        num=0
        for sku in skus:
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
            num+=1
        return self.make_request(data,'GetLowestOfferListingsForSKU')
    
def main():
    p = Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")
    comp = p.get_competitive_pricing_for_sku('A21TJRUUN4KGV', ['FBA12248','FBB12248'])
    our = p.get_my_pricing_for_sku('A21TJRUUN4KGV', ['FBA12248','FBB12248'])
    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()