Subversion Repositories SmartDukaan

Rev

Rev 12434 | Rev 12437 | 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
68
                    temp['sellingPrice'] = amount
69
                    temp['promoPrice'] = amount
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):
12436 kshitij.so 97
        print response.text
12430 kshitij.so 98
        spString = re.sub('<\?.*\?>','',response.text)
99
        spString = "<dom>" + spString + "</dom>"
100
        dom = parseString(spString)
101
        skuOffers = dom.getElementsByTagName('GetMyPriceForSKUResult')
102
        skuMap = {}
103
        for skuOffer in skuOffers:
104
            status = skuOffer.attributes.items()[0][1]
105
            sku = skuOffer.attributes.items()[1][1]
106
            asin = skuOffer.getElementsByTagName('ASIN')[0].firstChild.nodeValue
12434 kshitij.so 107
            print "fetching details of ",sku
12430 kshitij.so 108
            for offer in skuOffer.getElementsByTagName('Offers'):
109
                temp = {}
12436 kshitij.so 110
                try:
111
                    promoPrice = offer.getElementsByTagName('LandedPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
112
                    regularPrice = offer.getElementsByTagName('RegularPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
113
                    temp['sellingPrice'] = regularPrice
114
                    temp['promoPrice'] = promoPrice
115
                    if promoPrice == regularPrice:
116
                        temp['promotion'] = False
117
                    else:
118
                        temp['promotion'] = True
119
                    temp['status'] = status
120
                    temp['asin'] = asin
121
                    temp['notOurSku'] = False
122
                    temp['fulfillmentChannel'] ='AMAZON'
123
                    temp['shippingTime'] =  '0-0'
124
                    temp['rating'] = '0'
125
                except:
126
                    pass
127
                skuMap[sku]=temp     
12430 kshitij.so 128
        return skuMap    
12363 kshitij.so 129
 
12430 kshitij.so 130
 
131
    def calc_signature(self, method, request_description):
132
        sig_data = method + '\n' + self.domain.replace('https://', '').lower() + '\n' + self.uri + '\n' + request_description
133
        return base64.b64encode(hmac.new(str(self.secret_key), sig_data, hashlib.sha256).digest())
12363 kshitij.so 134
 
12430 kshitij.so 135
    def get_timestamp(self):
136
        return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
137
 
138
 
139
class Products(MWS):
140
 
141
    URI = '/Products/2011-10-01'
142
    VERSION = '2011-10-01'
143
    NS = '{https://mws-eu.amazonservices.com/Products/2011-10-01}'
144
 
145
 
146
    def get_my_pricing_for_sku(self, marketplaceid, skus):
147
 
148
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
149
        num=0
150
        for sku in skus:
151
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
152
            num+=1
153
        return self.make_request(data,'GetMyPriceForSKU')
154
 
155
 
156
    def get_competitive_pricing_for_sku(self, marketplaceid, skus):
157
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
158
        num=0
159
        for sku in skus:
160
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
161
            num+=1
162
        return self.make_request(data,'GetLowestOfferListingsForSKU')
163
 
164
def main():
165
    p = Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")
12436 kshitij.so 166
    comp = p.get_competitive_pricing_for_sku('A21TJRUUN4KGV', ['FBA10049'])
167
    our = p.get_my_pricing_for_sku('A21TJRUUN4KGV', ['FBA10049'])
168
    print comp
169
    print our
170
#    print comp.get('FBA12248')
171
#    print our.get('FBA12248')
172
#    x = (our.get('FBA12248'))
173
#    x['sellingPrice']=41089
174
#    l = (comp.get('FBA12248'))
175
#    l.append((our.get('FBA12248')))
176
#    print sorted(l, key=itemgetter('promoPrice','notOurSku'))
12430 kshitij.so 177
 
178
 
179
 
180
 
181
 
182
 
183
if __name__=='__main__':
184
    main()