Subversion Repositories SmartDukaan

Rev

Rev 12430 | Rev 12436 | 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
                if len(info)==3:
12363 kshitij.so 64
                    break
12430 kshitij.so 65
                temp = {}
66
                amount = offer.getElementsByTagName('Amount')[0].firstChild.nodeValue
67
                temp['sellingPrice'] = amount
68
                temp['promoPrice'] = amount
69
                temp['fulfillmentChannel'] = offer.getElementsByTagName('FulfillmentChannel')[0].firstChild.nodeValue
12363 kshitij.so 70
                try:
12430 kshitij.so 71
                    temp['shippingTime'] = (offer.getElementsByTagName('Max')[0].firstChild.nodeValue).replace('days','')
12363 kshitij.so 72
                except:
12430 kshitij.so 73
                    temp['shippingTime'] = '0-0'
74
                try:
75
                    temp['rating'] = (offer.getElementsByTagName('SellerPositiveFeedbackRating')[0].firstChild.nodeValue)
76
                    if temp['rating'] == 'Just Launched':
77
                        temp['rating'] = '0'
78
                    else:
79
                        str_rating = temp['rating'].replace('-',' ').replace('%','')
80
                        a =  str_rating.split()
81
                        l = []
82
                        for x in a:
83
                            if x.isdigit():
84
                                l.append(x)
85
                        temp['rating'] = l[0]
86
                except:
87
                    temp['rating'] = '0'
88
                temp['notOurSku'] = True
89
                info.append(temp)
90
            offerMap[sku]=info        
91
        return offerMap
92
 
93
    def parse_my_pricing_response(self,response):
94
        spString = re.sub('<\?.*\?>','',response.text)
95
        spString = "<dom>" + spString + "</dom>"
96
        dom = parseString(spString)
97
        skuOffers = dom.getElementsByTagName('GetMyPriceForSKUResult')
98
        skuMap = {}
99
        for skuOffer in skuOffers:
100
            status = skuOffer.attributes.items()[0][1]
101
            sku = skuOffer.attributes.items()[1][1]
102
            asin = skuOffer.getElementsByTagName('ASIN')[0].firstChild.nodeValue
12434 kshitij.so 103
            print "fetching details of ",sku
12430 kshitij.so 104
            for offer in skuOffer.getElementsByTagName('Offers'):
105
                temp = {}
106
                promoPrice = offer.getElementsByTagName('LandedPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
107
                regularPrice = offer.getElementsByTagName('RegularPrice')[0].getElementsByTagName('Amount')[0].firstChild.nodeValue
108
                temp['sellingPrice'] = regularPrice
109
                temp['promoPrice'] = promoPrice
110
                if promoPrice == regularPrice:
111
                    temp['promotion'] = False
112
                else:
113
                    temp['promotion'] = True
114
                temp['status'] = status
115
                temp['asin'] = asin
116
                temp['notOurSku'] = False
117
                temp['fulfillmentChannel'] ='AMAZON'
118
                temp['shippingTime'] =  '0-0'
119
                temp['rating'] = '0'
120
            skuMap[sku]=temp     
121
        return skuMap    
12363 kshitij.so 122
 
12430 kshitij.so 123
 
124
    def calc_signature(self, method, request_description):
125
        sig_data = method + '\n' + self.domain.replace('https://', '').lower() + '\n' + self.uri + '\n' + request_description
126
        return base64.b64encode(hmac.new(str(self.secret_key), sig_data, hashlib.sha256).digest())
12363 kshitij.so 127
 
12430 kshitij.so 128
    def get_timestamp(self):
129
        return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
130
 
131
 
132
class Products(MWS):
133
 
134
    URI = '/Products/2011-10-01'
135
    VERSION = '2011-10-01'
136
    NS = '{https://mws-eu.amazonservices.com/Products/2011-10-01}'
137
 
138
 
139
    def get_my_pricing_for_sku(self, marketplaceid, skus):
140
 
141
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
142
        num=0
143
        for sku in skus:
144
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
145
            num+=1
146
        return self.make_request(data,'GetMyPriceForSKU')
147
 
148
 
149
    def get_competitive_pricing_for_sku(self, marketplaceid, skus):
150
        data = dict(SellerId=self.merchant_id, MarketplaceId=marketplaceid)
151
        num=0
152
        for sku in skus:
153
            data['SellerSKUList.SellerSKU.%d' % (num + 1)] = sku
154
            num+=1
155
        return self.make_request(data,'GetLowestOfferListingsForSKU')
156
 
157
def main():
158
    p = Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")
159
    comp = p.get_competitive_pricing_for_sku('A21TJRUUN4KGV', ['FBA12248','FBB12248'])
160
    our = p.get_my_pricing_for_sku('A21TJRUUN4KGV', ['FBA12248','FBB12248'])
161
    print comp.get('FBA12248')
162
    print our.get('FBA12248')
163
    x = (our.get('FBA12248'))
164
    x['sellingPrice']=41089
165
    l = (comp.get('FBA12248'))
166
    l.append((our.get('FBA12248')))
167
    print sorted(l, key=itemgetter('promoPrice','notOurSku'))
168
 
169
 
170
 
171
 
172
 
173
 
174
if __name__=='__main__':
175
    main()