Subversion Repositories SmartDukaan

Rev

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