Subversion Repositories SmartDukaan

Rev

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