Subversion Repositories SmartDukaan

Rev

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