Subversion Repositories SmartDukaan

Rev

Rev 12440 | Rev 12597 | 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
9
from operator import itemgetter
12363 kshitij.so 10
 
11
 
12430 kshitij.so 12
class MWS(object):
13
    URI = "/"
14
    VERSION = "2009-01-01"
15
    NS = ''
12363 kshitij.so 16
 
12430 kshitij.so 17
    def __init__(self, access_key, secret_key, merchant_id,
18
                 domain='https://mws-eu.amazonservices.com', uri="", version=""):
19
        self.access_key = access_key
20
        self.secret_key = secret_key
21
        self.merchant_id = merchant_id
22
        self.domain = domain
23
        self.uri = uri or self.URI
24
        self.version = version or self.VERSION
12363 kshitij.so 25
 
12430 kshitij.so 26
    def make_request(self, extra_data, action,method="GET", **kwargs):
12363 kshitij.so 27
 
12430 kshitij.so 28
        params = {
29
            'AWSAccessKeyId': self.access_key,
30
            'SignatureVersion': '2',
31
            'Timestamp': self.get_timestamp(),
32
            'Version': self.version,
33
            'SignatureMethod': 'HmacSHA256',
34
            'Action': action
35
        }
36
        if action=='GetLowestOfferListingsForSKU':
37
            params['ExcludeMe']='true'
38
        params.update(extra_data)
39
        request_description = '&'.join(['%s=%s' % (k, urllib.quote(params[k], safe='-_.~').encode('utf-8')) for k in sorted(params)])
40
        signature = self.calc_signature(method, request_description)
41
        url = '%s%s?%s&Signature=%s' % (self.domain, self.uri, request_description, urllib.quote(signature))
42
        headers = {'User-Agent': 'AmazonJavascriptScratchpad/1.0 (Language=Python)'}
43
        headers.update(kwargs.get('extra_headers', {}))
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 = {}
58
        for skuOffer in skuOffers:
59
            status = skuOffer.attributes.items()[0][1]
60
            sku = skuOffer.attributes.items()[1][1]
12363 kshitij.so 61
            info = []
12430 kshitij.so 62
            for offer in skuOffer.getElementsByTagName('LowestOfferListing'):
63
                temp = {}
12363 kshitij.so 64
                try:
12436 kshitij.so 65
                    if len(info)==3:
66
                        break
67
                    amount = offer.getElementsByTagName('Amount')[0].firstChild.nodeValue
12482 kshitij.so 68
                    temp['sellingPrice'] = float(amount)
69
                    temp['promoPrice'] = float(amount)
12436 kshitij.so 70
                    temp['fulfillmentChannel'] = offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValue
71
                    try:
72
                        temp['shippingTime'] = (offer.getElementsByTagName('Max')[0].firstChild.nodeValue).replace('days','')
73
                    except:
74
                        temp['shippingTime'] = '0-0'
75
                    try:
76
                        temp['rating'] = (offer.getElementsByTagName('SellerPositiveFeedbackRating')[0].firstChild.nodeValue)
77
                        if temp['rating'] == 'Just Launched':
78
                            temp['rating'] = '0'
79
                        else:
80
                            str_rating = temp['rating'].replace('-',' ').replace('%','')
81
                            a =  str_rating.split()
82
                            l = []
83
                            for x in a:
84
                                if x.isdigit():
85
                                    l.append(x)
86
                            temp['rating'] = l[0]
87
                    except:
12430 kshitij.so 88
                        temp['rating'] = '0'
89
                except:
12436 kshitij.so 90
                    pass
12430 kshitij.so 91
                temp['notOurSku'] = True
92
                info.append(temp)
12436 kshitij.so 93
                offerMap[sku]=info        
12430 kshitij.so 94
        return offerMap
95
 
96
    def parse_my_pricing_response(self,response):
97
        spString = re.sub('<\?.*\?>','',response.text)
98
        spString = "<dom>" + spString + "</dom>"
99
        dom = parseString(spString)
100
        skuOffers = dom.getElementsByTagName('GetMyPriceForSKUResult')
101
        skuMap = {}
102
        for skuOffer in skuOffers:
12438 kshitij.so 103
            try:
104
                status = skuOffer.attributes.items()[0][1]
105
                sku = skuOffer.attributes.items()[1][1]
106
                asin = skuOffer.getElementsByTagName('ASIN')[0].firstChild.nodeValue
107
            except:
108
                continue
12430 kshitij.so 109
            for offer in skuOffer.getElementsByTagName('Offers'):
110
                temp = {}
12436 kshitij.so 111
                try:
112
                    promoPrice = offer.getElementsByTagName('LandedPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
113
                    regularPrice = offer.getElementsByTagName('RegularPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
12482 kshitij.so 114
                    temp['sellingPrice'] = float(regularPrice)
115
                    temp['promoPrice'] = float(promoPrice)
12436 kshitij.so 116
                    if promoPrice == regularPrice:
117
                        temp['promotion'] = False
118
                    else:
119
                        temp['promotion'] = True
120
                    temp['status'] = status
121
                    temp['asin'] = asin
122
                    temp['notOurSku'] = False
123
                    temp['fulfillmentChannel'] ='AMAZON'
124
                    temp['shippingTime'] =  '0-0'
125
                    temp['rating'] = '0'
126
                except:
127
                    pass
128
                skuMap[sku]=temp     
12430 kshitij.so 129
        return skuMap    
12363 kshitij.so 130
 
12430 kshitij.so 131
 
132
    def calc_signature(self, method, request_description):
133
        sig_data = method + '\n' + self.domain.replace('https://', '').lower() + '\n' + self.uri + '\n' + request_description
134
        return base64.b64encode(hmac.new(str(self.secret_key), sig_data, hashlib.sha256).digest())
12363 kshitij.so 135
 
12430 kshitij.so 136
    def get_timestamp(self):
137
        return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
138
 
139
 
140
class Products(MWS):
141
 
142
    URI = '/Products/2011-10-01'
143
    VERSION = '2011-10-01'
144
    NS = '{https://mws-eu.amazonservices.com/Products/2011-10-01}'
145
 
146
 
147
    def get_my_pricing_for_sku(self, marketplaceid, skus):
148
 
149
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
150
        num=0
151
        for sku in skus:
152
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
153
            num+=1
154
        return self.make_request(data,'GetMyPriceForSKU')
155
 
156
 
157
    def get_competitive_pricing_for_sku(self, marketplaceid, skus):
158
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
159
        num=0
160
        for sku in skus:
161
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
162
            num+=1
163
        return self.make_request(data,'GetLowestOfferListingsForSKU')
164
 
165
def main():
166
    p = Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")
12482 kshitij.so 167
    comp = p.get_competitive_pricing_for_sku('A21TJRUUN4KGV', ['FBA16293'])
168
    our = p.get_my_pricing_for_sku('A21TJRUUN4KGV', ['FBA3024'])
12436 kshitij.so 169
    print comp
170
    print our
12482 kshitij.so 171
    #print our.get('promotion')
12436 kshitij.so 172
#    print comp.get('FBA12248')
173
#    print our.get('FBA12248')
174
#    x = (our.get('FBA12248'))
175
#    x['sellingPrice']=41089
176
#    l = (comp.get('FBA12248'))
177
#    l.append((our.get('FBA12248')))
178
#    print sorted(l, key=itemgetter('promoPrice','notOurSku'))
12430 kshitij.so 179
 
180
 
181
 
182
 
183
 
184
 
185
if __name__=='__main__':
186
    main()