Subversion Repositories SmartDukaan

Rev

Rev 15688 | Rev 20315 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
12430 kshitij.so 1
from xml.dom.minidom import parseString
12363 kshitij.so 2
import re
12430 kshitij.so 3
import urllib
4
import hashlib
5
import hmac
6
import base64
7
from time import strftime, gmtime
8
from requests import request
12363 kshitij.so 9
 
10
 
12430 kshitij.so 11
class MWS(object):
12
    URI = "/"
13
    VERSION = "2009-01-01"
14
    NS = ''
12363 kshitij.so 15
 
12430 kshitij.so 16
    def __init__(self, access_key, secret_key, merchant_id,
17
                 domain='https://mws-eu.amazonservices.com', uri="", version=""):
18
        self.access_key = access_key
19
        self.secret_key = secret_key
20
        self.merchant_id = merchant_id
21
        self.domain = domain
22
        self.uri = uri or self.URI
23
        self.version = version or self.VERSION
12363 kshitij.so 24
 
12430 kshitij.so 25
    def make_request(self, extra_data, action,method="GET", **kwargs):
12363 kshitij.so 26
 
12430 kshitij.so 27
        params = {
28
            'AWSAccessKeyId': self.access_key,
29
            'SignatureVersion': '2',
30
            'Timestamp': self.get_timestamp(),
31
            'Version': self.version,
32
            'SignatureMethod': 'HmacSHA256',
33
            'Action': action
34
        }
35
        if action=='GetLowestOfferListingsForSKU':
36
            params['ExcludeMe']='true'
20312 kshitij.so 37
        if action =='GetLowestOfferListingsForASIN':
38
            params['ItemCondition'] = 'New'
12430 kshitij.so 39
        params.update(extra_data)
40
        request_description = '&'.join(['%s=%s' % (k, urllib.quote(params[k], safe='-_.~').encode('utf-8')) for k in sorted(params)])
41
        signature = self.calc_signature(method, request_description)
42
        url = '%s%s?%s&Signature=%s' % (self.domain, self.uri, request_description, urllib.quote(signature))
15688 kshitij.so 43
        print url
12801 kshitij.so 44
        #headers = {'User-Agent': 'AmazonJavascriptScratchpad/1.0 (Language=Python)'}
45
        #headers.update(kwargs.get('extra_headers', {}))
12430 kshitij.so 46
        response = request(method, url)
47
        if action=='GetLowestOfferListingsForSKU':
48
            return self.parse_competitor_pricing_response(response)
49
        elif action=='GetMyPriceForSKU':
50
            return self.parse_my_pricing_response(response)
12853 kshitij.so 51
        elif action=='GetProductCategoriesForSKU':
52
            return self.parse_product_category_for_sku(response)
15688 kshitij.so 53
        elif action=='GetMatchingProductForId':
54
            return self.parse_product_attributes(response)
20312 kshitij.so 55
        elif action=='GetLowestOfferListingsForASIN':
56
            return self.parse_lowest_pricing_asins(response)
12430 kshitij.so 57
        else:
58
            raise
12363 kshitij.so 59
 
12853 kshitij.so 60
    def parse_product_category_for_sku(self,response):
20312 kshitij.so 61
        print response.text
12853 kshitij.so 62
        browseNodes = []
12908 kshitij.so 63
        #node = "" 
12853 kshitij.so 64
        spString = re.sub('<\?.*\?>','',response.text)
65
        spString = "<dom>" + spString + "</dom>"
66
        dom = parseString(spString)
67
        selfTag = dom.getElementsByTagName('Self')
68
        for element in selfTag:
69
            temp = []
70
            browsingNodes = element.getElementsByTagName('ProductCategoryName')
71
            for browsingNode in browsingNodes:
72
                temp.append(browsingNode.firstChild.nodeValue)
73
            browseNodes.append(temp)
74
        return browseNodes
75
 
15688 kshitij.so 76
    def parse_product_attributes(self,response):
77
        spString = re.sub('<\?.*\?>','',response.text)
78
        spString = "<dom>" + spString + "</dom>"
79
        dom = parseString(spString)
80
        sku = dom.getElementsByTagName("GetMatchingProductForIdResult")[0].attributes.items()[2][1]
81
        dimensions = dom.getElementsByTagName("ns2:PackageDimensions")
82
        for dimension in dimensions:
83
            height = dimension.getElementsByTagName("ns2:Height")[0].firstChild.nodeValue #Inch
84
            length = dimension.getElementsByTagName("ns2:Length")[0].firstChild.nodeValue #Inch
85
            width = dimension.getElementsByTagName("ns2:Width")[0].firstChild.nodeValue #Inch
86
            weight = dimension.getElementsByTagName("ns2:Weight")[0].firstChild.nodeValue #Pounds
87
            return {'sku':sku,'length':length,'width':width,'height':height,'weight':weight}
20312 kshitij.so 88
 
89
    def parse_lowest_pricing_asins(self,response):
90
        #GetLowestOfferListingsForASINResult
91
        spString = re.sub('<\?.*\?>','',response.text)
92
        spString = "<dom>" + spString + "</dom>"
93
        dom = parseString(spString)
94
        asinOffers = dom.getElementsByTagName('GetLowestOfferListingsForASINResult')
95
        asinMap = {}
96
        for asinOffer in asinOffers:
97
            asin = asinOffer.attributes.items()[1][1]
98
            asinMap[asin] = 0.0
99
            for offer in asinOffer.getElementsByTagName('LowestOfferListing'):
100
                price =  offer.getElementsByTagName('Amount')[0].firstChild.nodeValue
101
                asinMap[asin] = price 
102
                break
103
        return asinMap
15688 kshitij.so 104
 
20312 kshitij.so 105
 
12430 kshitij.so 106
    def parse_competitor_pricing_response(self,response):
107
        spString = re.sub('<\?.*\?>','',response.text)
108
        spString = "<dom>" + spString + "</dom>"
109
        dom = parseString(spString)
110
        skuOffers = dom.getElementsByTagName('GetLowestOfferListingsForSKUResult')
111
        offerMap = {}
12597 kshitij.so 112
        otherInfo = {}
12430 kshitij.so 113
        for skuOffer in skuOffers:
114
            status = skuOffer.attributes.items()[0][1]
115
            sku = skuOffer.attributes.items()[1][1]
12363 kshitij.so 116
            info = []
12430 kshitij.so 117
            for offer in skuOffer.getElementsByTagName('LowestOfferListing'):
118
                temp = {}
12363 kshitij.so 119
                try:
12436 kshitij.so 120
                    if len(info)==3:
121
                        break
122
                    amount = offer.getElementsByTagName('Amount')[0].firstChild.nodeValue
12482 kshitij.so 123
                    temp['sellingPrice'] = float(amount)
124
                    temp['promoPrice'] = float(amount)
12436 kshitij.so 125
                    temp['fulfillmentChannel'] = offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValue
126
                    try:
127
                        temp['shippingTime'] = (offer.getElementsByTagName('Max')[0].firstChild.nodeValue).replace('days','')
128
                    except:
129
                        temp['shippingTime'] = '0-0'
130
                    try:
131
                        temp['rating'] = (offer.getElementsByTagName('SellerPositiveFeedbackRating')[0].firstChild.nodeValue)
132
                        if temp['rating'] == 'Just Launched':
12801 kshitij.so 133
                            temp['rating'] = '100'
12436 kshitij.so 134
                        else:
135
                            str_rating = temp['rating'].replace('-',' ').replace('%','')
136
                            a =  str_rating.split()
137
                            l = []
138
                            for x in a:
139
                                if x.isdigit():
140
                                    l.append(x)
141
                            temp['rating'] = l[0]
142
                    except:
12430 kshitij.so 143
                        temp['rating'] = '0'
144
                except:
12436 kshitij.so 145
                    pass
12430 kshitij.so 146
                temp['notOurSku'] = True
147
                info.append(temp)
12597 kshitij.so 148
                offerMap[sku]=info
149
        for skuOffer in skuOffers:
150
            sku = skuOffer.attributes.items()[1][1]
151
            temp = {}
152
            temp['lowestMfnIgnored']=0.0
153
            temp['isLowestMfnIgnored']=False
154
            temp['lowestFba']=0.0
155
            temp['isLowestFba']=False
156
            temp['lowestMfn']=0.0
157
            temp['isLowestMfn']=False
158
            for offer in skuOffer.getElementsByTagName('LowestOfferListing'):
159
                try:
160
                    fulfillmentChannel = offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValue
161
                    amount = offer.getElementsByTagName('Amount')[0].firstChild.nodeValue
162
                    try:
163
                        rating = (offer.getElementsByTagName('SellerPositiveFeedbackRating')[0].firstChild.nodeValue)
164
                        if rating == 'Just Launched':
12801 kshitij.so 165
                            rating = 100
12597 kshitij.so 166
                        else:
167
                            str_rating = rating.replace('-',' ').replace('%','')
168
                            a =  str_rating.split()
169
                            l = []
170
                            for x in a:
171
                                if x.isdigit():
172
                                    l.append(x)
173
                            rating = int(l[0])
174
                    except:
175
                        rating = 0
176
                    if fulfillmentChannel=='Merchant' and not temp['isLowestMfnIgnored'] and not temp['isLowestMfn'] and rating < 60:
177
                        temp['lowestMfnIgnored'] = float(amount)
178
                        temp['isLowestMfnIgnored']=True
179
                    elif fulfillmentChannel=='Merchant' and not temp['isLowestMfn'] and rating > 60:
180
                        temp['lowestMfn'] = float(amount)
181
                        temp['isLowestMfn']=True
182
                    elif fulfillmentChannel=='Amazon' and not temp['isLowestFba']:
183
                        temp['lowestFba'] = float(amount)
184
                        temp['isLowestFba']=True
185
                    else:
186
                        pass
187
                except:
188
                    pass
189
                otherInfo[sku]=temp
190
        return offerMap, otherInfo
12430 kshitij.so 191
 
192
    def parse_my_pricing_response(self,response):
193
        spString = re.sub('<\?.*\?>','',response.text)
194
        spString = "<dom>" + spString + "</dom>"
195
        dom = parseString(spString)
196
        skuOffers = dom.getElementsByTagName('GetMyPriceForSKUResult')
197
        skuMap = {}
198
        for skuOffer in skuOffers:
12438 kshitij.so 199
            try:
200
                status = skuOffer.attributes.items()[0][1]
201
                sku = skuOffer.attributes.items()[1][1]
202
                asin = skuOffer.getElementsByTagName('ASIN')[0].firstChild.nodeValue
12908 kshitij.so 203
                skuMap[sku]={}
12438 kshitij.so 204
            except:
205
                continue
12908 kshitij.so 206
            for offer in skuOffer.getElementsByTagName('Offer'):
207
                offerSku = offer.getElementsByTagName('SellerSKU')[0].firstChild.nodeValue
208
                fcChannel =  offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValue
209
                if not (offerSku==sku and fcChannel=='AMAZON'):
210
                    continue
12430 kshitij.so 211
                temp = {}
12436 kshitij.so 212
                try:
213
                    promoPrice = offer.getElementsByTagName('LandedPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
214
                    regularPrice = offer.getElementsByTagName('RegularPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
12482 kshitij.so 215
                    temp['sellingPrice'] = float(regularPrice)
216
                    temp['promoPrice'] = float(promoPrice)
12436 kshitij.so 217
                    if promoPrice == regularPrice:
218
                        temp['promotion'] = False
219
                    else:
220
                        temp['promotion'] = True
221
                    temp['status'] = status
222
                    temp['asin'] = asin
223
                    temp['notOurSku'] = False
224
                    temp['fulfillmentChannel'] ='AMAZON'
225
                    temp['shippingTime'] =  '0-0'
226
                    temp['rating'] = '0'
227
                except:
228
                    pass
229
                skuMap[sku]=temp     
12430 kshitij.so 230
        return skuMap    
12363 kshitij.so 231
 
12430 kshitij.so 232
 
233
    def calc_signature(self, method, request_description):
234
        sig_data = method + '\n' + self.domain.replace('https://', '').lower() + '\n' + self.uri + '\n' + request_description
235
        return base64.b64encode(hmac.new(str(self.secret_key), sig_data, hashlib.sha256).digest())
12363 kshitij.so 236
 
12430 kshitij.so 237
    def get_timestamp(self):
238
        return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
239
 
240
 
241
class Products(MWS):
242
 
243
    URI = '/Products/2011-10-01'
244
    VERSION = '2011-10-01'
245
    NS = '{https://mws-eu.amazonservices.com/Products/2011-10-01}'
246
 
247
 
248
    def get_my_pricing_for_sku(self, marketplaceid, skus):
249
 
250
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
251
        num=0
252
        for sku in skus:
253
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
254
            num+=1
255
        return self.make_request(data,'GetMyPriceForSKU')
256
 
257
 
258
    def get_competitive_pricing_for_sku(self, marketplaceid, skus):
259
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
260
        num=0
261
        for sku in skus:
262
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
263
            num+=1
264
        return self.make_request(data,'GetLowestOfferListingsForSKU')
265
 
12853 kshitij.so 266
    def get_product_category_for_sku(self, marketplaceid, sku):
267
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
268
        data['SellerSKU'] = sku
269
        return self.make_request(data,'GetProductCategoriesForSKU')
270
 
15688 kshitij.so 271
    def get_product_attributes_for_sku(self, marketplaceid, skus):
272
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
273
        num=0
274
        for sku in skus:
275
            data['IdList.Id.%d' % (num + 1)] = sku
276
            num+=1
20312 kshitij.so 277
        data['IdType'] = 'ASIN'
15688 kshitij.so 278
        print data
279
        return self.make_request(data,'GetMatchingProductForId')
12853 kshitij.so 280
 
20312 kshitij.so 281
    def get_competitive_pricing_for_asin(self, marketplaceid, asins):
282
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
283
        num=0
284
        for asin in asins:
285
            data['ASINList.ASIN.%d' % (num + 1)] = asin
286
            num+=1
287
        return self.make_request(data,'GetLowestOfferListingsForASIN')
15688 kshitij.so 288
 
20312 kshitij.so 289
 
290
 
12430 kshitij.so 291
def main():
292
    p = Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")
20312 kshitij.so 293
    print p.get_competitive_pricing_for_asin("A21TJRUUN4KGV", ["B0168L23VS", "B017LRFNBK", "B01B7LZS8O", "B01CTWJIX6", "B01BHWRDVS", "B015J6B94U", "B015U5MBVA", "B01ALFQM82", "B0188ZHVZU", "B01CZPKANO", "B018K47ZK0", "B01BIYAXGW", "B01AUXJYMQ", "B01AI57N6K", "B01DY912SM", "B0119F11PW", "B0191UMYV2", "B017G6BPZY", "B01DDE8U88", "B01BGMMJZO"])
12430 kshitij.so 294
 
295
if __name__=='__main__':
12801 kshitij.so 296
    main()