Subversion Repositories SmartDukaan

Rev

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