Subversion Repositories SmartDukaan

Rev

Rev 20315 | 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))
12801 kshitij.so 43
        #headers = {'User-Agent': 'AmazonJavascriptScratchpad/1.0 (Language=Python)'}
44
        #headers.update(kwargs.get('extra_headers', {}))
12430 kshitij.so 45
        response = request(method, url)
46
        if action=='GetLowestOfferListingsForSKU':
47
            return self.parse_competitor_pricing_response(response)
48
        elif action=='GetMyPriceForSKU':
49
            return self.parse_my_pricing_response(response)
12853 kshitij.so 50
        elif action=='GetProductCategoriesForSKU':
51
            return self.parse_product_category_for_sku(response)
15688 kshitij.so 52
        elif action=='GetMatchingProductForId':
53
            return self.parse_product_attributes(response)
20312 kshitij.so 54
        elif action=='GetLowestOfferListingsForASIN':
55
            return self.parse_lowest_pricing_asins(response)
20324 kshitij.so 56
        elif action == 'GetMatchingProduct':
57
            return self.parse_get_matching_product(response)
12430 kshitij.so 58
        else:
59
            raise
12363 kshitij.so 60
 
20324 kshitij.so 61
    def parse_get_matching_product(self, response):
62
        spString = re.sub('<\?.*\?>','',response.text)
63
        spString = "<dom>" + spString + "</dom>"
64
        dom = parseString(spString)
65
        asinStatuses = dom.getElementsByTagName('GetMatchingProductResult')
66
        asinMap = {}
67
        for asinStatus in asinStatuses:
68
            #print asinStatus.attributes.items()
69
            status = asinStatus.attributes.items()[0][1]
70
            asin = asinStatus.attributes.items()[1][1]
71
            asinMap[asin] = status
72
        return asinMap
73
 
12853 kshitij.so 74
    def parse_product_category_for_sku(self,response):
75
        browseNodes = []
12908 kshitij.so 76
        #node = "" 
12853 kshitij.so 77
        spString = re.sub('<\?.*\?>','',response.text)
78
        spString = "<dom>" + spString + "</dom>"
79
        dom = parseString(spString)
80
        selfTag = dom.getElementsByTagName('Self')
81
        for element in selfTag:
82
            temp = []
83
            browsingNodes = element.getElementsByTagName('ProductCategoryName')
84
            for browsingNode in browsingNodes:
85
                temp.append(browsingNode.firstChild.nodeValue)
86
            browseNodes.append(temp)
87
        return browseNodes
88
 
15688 kshitij.so 89
    def parse_product_attributes(self,response):
90
        spString = re.sub('<\?.*\?>','',response.text)
91
        spString = "<dom>" + spString + "</dom>"
92
        dom = parseString(spString)
93
        sku = dom.getElementsByTagName("GetMatchingProductForIdResult")[0].attributes.items()[2][1]
94
        dimensions = dom.getElementsByTagName("ns2:PackageDimensions")
95
        for dimension in dimensions:
96
            height = dimension.getElementsByTagName("ns2:Height")[0].firstChild.nodeValue #Inch
97
            length = dimension.getElementsByTagName("ns2:Length")[0].firstChild.nodeValue #Inch
98
            width = dimension.getElementsByTagName("ns2:Width")[0].firstChild.nodeValue #Inch
99
            weight = dimension.getElementsByTagName("ns2:Weight")[0].firstChild.nodeValue #Pounds
100
            return {'sku':sku,'length':length,'width':width,'height':height,'weight':weight}
20312 kshitij.so 101
 
102
    def parse_lowest_pricing_asins(self,response):
103
        #GetLowestOfferListingsForASINResult
104
        spString = re.sub('<\?.*\?>','',response.text)
105
        spString = "<dom>" + spString + "</dom>"
106
        dom = parseString(spString)
107
        asinOffers = dom.getElementsByTagName('GetLowestOfferListingsForASINResult')
108
        asinMap = {}
109
        for asinOffer in asinOffers:
110
            asin = asinOffer.attributes.items()[1][1]
111
            asinMap[asin] = 0.0
112
            for offer in asinOffer.getElementsByTagName('LowestOfferListing'):
113
                price =  offer.getElementsByTagName('Amount')[0].firstChild.nodeValue
20315 kshitij.so 114
                asinMap[asin] = float(price) 
20312 kshitij.so 115
                break
116
        return asinMap
15688 kshitij.so 117
 
20312 kshitij.so 118
 
12430 kshitij.so 119
    def parse_competitor_pricing_response(self,response):
120
        spString = re.sub('<\?.*\?>','',response.text)
121
        spString = "<dom>" + spString + "</dom>"
122
        dom = parseString(spString)
123
        skuOffers = dom.getElementsByTagName('GetLowestOfferListingsForSKUResult')
124
        offerMap = {}
12597 kshitij.so 125
        otherInfo = {}
12430 kshitij.so 126
        for skuOffer in skuOffers:
127
            status = skuOffer.attributes.items()[0][1]
128
            sku = skuOffer.attributes.items()[1][1]
12363 kshitij.so 129
            info = []
12430 kshitij.so 130
            for offer in skuOffer.getElementsByTagName('LowestOfferListing'):
131
                temp = {}
12363 kshitij.so 132
                try:
12436 kshitij.so 133
                    if len(info)==3:
134
                        break
135
                    amount = offer.getElementsByTagName('Amount')[0].firstChild.nodeValue
12482 kshitij.so 136
                    temp['sellingPrice'] = float(amount)
137
                    temp['promoPrice'] = float(amount)
12436 kshitij.so 138
                    temp['fulfillmentChannel'] = offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValue
139
                    try:
140
                        temp['shippingTime'] = (offer.getElementsByTagName('Max')[0].firstChild.nodeValue).replace('days','')
141
                    except:
142
                        temp['shippingTime'] = '0-0'
143
                    try:
144
                        temp['rating'] = (offer.getElementsByTagName('SellerPositiveFeedbackRating')[0].firstChild.nodeValue)
145
                        if temp['rating'] == 'Just Launched':
12801 kshitij.so 146
                            temp['rating'] = '100'
12436 kshitij.so 147
                        else:
148
                            str_rating = temp['rating'].replace('-',' ').replace('%','')
149
                            a =  str_rating.split()
150
                            l = []
151
                            for x in a:
152
                                if x.isdigit():
153
                                    l.append(x)
154
                            temp['rating'] = l[0]
155
                    except:
12430 kshitij.so 156
                        temp['rating'] = '0'
157
                except:
12436 kshitij.so 158
                    pass
12430 kshitij.so 159
                temp['notOurSku'] = True
160
                info.append(temp)
12597 kshitij.so 161
                offerMap[sku]=info
162
        for skuOffer in skuOffers:
163
            sku = skuOffer.attributes.items()[1][1]
164
            temp = {}
165
            temp['lowestMfnIgnored']=0.0
166
            temp['isLowestMfnIgnored']=False
167
            temp['lowestFba']=0.0
168
            temp['isLowestFba']=False
169
            temp['lowestMfn']=0.0
170
            temp['isLowestMfn']=False
171
            for offer in skuOffer.getElementsByTagName('LowestOfferListing'):
172
                try:
173
                    fulfillmentChannel = offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValue
174
                    amount = offer.getElementsByTagName('Amount')[0].firstChild.nodeValue
175
                    try:
176
                        rating = (offer.getElementsByTagName('SellerPositiveFeedbackRating')[0].firstChild.nodeValue)
177
                        if rating == 'Just Launched':
12801 kshitij.so 178
                            rating = 100
12597 kshitij.so 179
                        else:
180
                            str_rating = rating.replace('-',' ').replace('%','')
181
                            a =  str_rating.split()
182
                            l = []
183
                            for x in a:
184
                                if x.isdigit():
185
                                    l.append(x)
186
                            rating = int(l[0])
187
                    except:
188
                        rating = 0
189
                    if fulfillmentChannel=='Merchant' and not temp['isLowestMfnIgnored'] and not temp['isLowestMfn'] and rating < 60:
190
                        temp['lowestMfnIgnored'] = float(amount)
191
                        temp['isLowestMfnIgnored']=True
192
                    elif fulfillmentChannel=='Merchant' and not temp['isLowestMfn'] and rating > 60:
193
                        temp['lowestMfn'] = float(amount)
194
                        temp['isLowestMfn']=True
195
                    elif fulfillmentChannel=='Amazon' and not temp['isLowestFba']:
196
                        temp['lowestFba'] = float(amount)
197
                        temp['isLowestFba']=True
198
                    else:
199
                        pass
200
                except:
201
                    pass
202
                otherInfo[sku]=temp
203
        return offerMap, otherInfo
12430 kshitij.so 204
 
205
    def parse_my_pricing_response(self,response):
206
        spString = re.sub('<\?.*\?>','',response.text)
207
        spString = "<dom>" + spString + "</dom>"
208
        dom = parseString(spString)
209
        skuOffers = dom.getElementsByTagName('GetMyPriceForSKUResult')
210
        skuMap = {}
211
        for skuOffer in skuOffers:
12438 kshitij.so 212
            try:
213
                status = skuOffer.attributes.items()[0][1]
214
                sku = skuOffer.attributes.items()[1][1]
215
                asin = skuOffer.getElementsByTagName('ASIN')[0].firstChild.nodeValue
12908 kshitij.so 216
                skuMap[sku]={}
12438 kshitij.so 217
            except:
218
                continue
12908 kshitij.so 219
            for offer in skuOffer.getElementsByTagName('Offer'):
220
                offerSku = offer.getElementsByTagName('SellerSKU')[0].firstChild.nodeValue
221
                fcChannel =  offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValue
222
                if not (offerSku==sku and fcChannel=='AMAZON'):
223
                    continue
12430 kshitij.so 224
                temp = {}
12436 kshitij.so 225
                try:
226
                    promoPrice = offer.getElementsByTagName('LandedPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
227
                    regularPrice = offer.getElementsByTagName('RegularPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
12482 kshitij.so 228
                    temp['sellingPrice'] = float(regularPrice)
229
                    temp['promoPrice'] = float(promoPrice)
12436 kshitij.so 230
                    if promoPrice == regularPrice:
231
                        temp['promotion'] = False
232
                    else:
233
                        temp['promotion'] = True
234
                    temp['status'] = status
235
                    temp['asin'] = asin
236
                    temp['notOurSku'] = False
237
                    temp['fulfillmentChannel'] ='AMAZON'
238
                    temp['shippingTime'] =  '0-0'
239
                    temp['rating'] = '0'
240
                except:
241
                    pass
242
                skuMap[sku]=temp     
12430 kshitij.so 243
        return skuMap    
12363 kshitij.so 244
 
12430 kshitij.so 245
 
246
    def calc_signature(self, method, request_description):
247
        sig_data = method + '\n' + self.domain.replace('https://', '').lower() + '\n' + self.uri + '\n' + request_description
248
        return base64.b64encode(hmac.new(str(self.secret_key), sig_data, hashlib.sha256).digest())
12363 kshitij.so 249
 
12430 kshitij.so 250
    def get_timestamp(self):
251
        return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
252
 
253
 
254
class Products(MWS):
255
 
256
    URI = '/Products/2011-10-01'
257
    VERSION = '2011-10-01'
258
    NS = '{https://mws-eu.amazonservices.com/Products/2011-10-01}'
259
 
260
 
261
    def get_my_pricing_for_sku(self, marketplaceid, skus):
262
 
263
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
264
        num=0
265
        for sku in skus:
266
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
267
            num+=1
268
        return self.make_request(data,'GetMyPriceForSKU')
269
 
270
 
271
    def get_competitive_pricing_for_sku(self, marketplaceid, skus):
272
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
273
        num=0
274
        for sku in skus:
275
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
276
            num+=1
277
        return self.make_request(data,'GetLowestOfferListingsForSKU')
278
 
12853 kshitij.so 279
    def get_product_category_for_sku(self, marketplaceid, sku):
280
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
281
        data['SellerSKU'] = sku
282
        return self.make_request(data,'GetProductCategoriesForSKU')
283
 
15688 kshitij.so 284
    def get_product_attributes_for_sku(self, marketplaceid, skus):
285
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
286
        num=0
287
        for sku in skus:
288
            data['IdList.Id.%d' % (num + 1)] = sku
289
            num+=1
20312 kshitij.so 290
        data['IdType'] = 'ASIN'
15688 kshitij.so 291
        return self.make_request(data,'GetMatchingProductForId')
12853 kshitij.so 292
 
20312 kshitij.so 293
    def get_competitive_pricing_for_asin(self, marketplaceid, asins):
294
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
295
        num=0
296
        for asin in asins:
297
            data['ASINList.ASIN.%d' % (num + 1)] = asin
298
            num+=1
299
        return self.make_request(data,'GetLowestOfferListingsForASIN')
15688 kshitij.so 300
 
20324 kshitij.so 301
    def get_matching_product(self, marketplaceid, asins):
302
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
303
        num=0
304
        for asin in asins:
305
            data['ASINList.ASIN.%d' % (num + 1)] = asin
306
            num+=1
307
        return self.make_request(data,'GetMatchingProduct')
20312 kshitij.so 308
 
309
 
20324 kshitij.so 310
 
12430 kshitij.so 311
def main():
312
    p = Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")
20324 kshitij.so 313
    print p.get_matching_product("A21TJRUUN4KGV", ["B016QBT87W","B0168L23VS"])
12430 kshitij.so 314
 
315
if __name__=='__main__':
12801 kshitij.so 316
    main()