Subversion Repositories SmartDukaan

Rev

Rev 20172 | Rev 20364 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
15869 kshitij.so 1
import urllib2
2
from BeautifulSoup import BeautifulSoup
3
import pymongo
4
import re
20347 kshitij.so 5
from dtr.utils.utils import to_java_date, getNlcPoints, DEAL_PRIORITY
15869 kshitij.so 6
import optparse
7
from datetime import datetime
16183 kshitij.so 8
import time
15869 kshitij.so 9
import smtplib
10
from email.mime.text import MIMEText
11
from email.mime.multipart import MIMEMultipart
15895 kshitij.so 12
from dtr.utils import ShopCluesScraper
13
import traceback
16019 kshitij.so 14
from dtr.storage.MemCache import MemCache
16184 kshitij.so 15
import chardet
15869 kshitij.so 16
 
17
con = None
18
parser = optparse.OptionParser()
19
parser.add_option("-m", "--m", dest="mongoHost",
20
                      default="localhost",
21
                      type="string", help="The HOST where the mongo server is running",
22
                      metavar="mongo_host")
16102 kshitij.so 23
parser.add_option("-r", "--reset", dest="reset",
24
                   default="False", type="string",
25
                   help="Reset Ranks?")
15869 kshitij.so 26
 
27
(options, args) = parser.parse_args()
28
 
16869 kshitij.so 29
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5,'PAYTM.COM':6}
15869 kshitij.so 30
bestSellers = []
31
baseUrl = "http://m.shopclues.com/products/getProductList/mobiles:top-selling-mobiles-and-tablets.html/%s/page=%s"
15895 kshitij.so 32
headers = {
33
            'User-Agent':'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36',
34
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
35
            'Accept-Language' : 'en-US,en;q=0.8',                     
36
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
16019 kshitij.so 37
            'Connection':'keep-alive'
15895 kshitij.so 38
        }
15869 kshitij.so 39
now = datetime.now()
16019 kshitij.so 40
mc = MemCache(options.mongoHost)
16099 kshitij.so 41
sc = ShopCluesScraper.ShopCluesScraper(findThumbnail=True)
15869 kshitij.so 42
 
16095 kshitij.so 43
bundledProducts = []
44
exceptionList = []
15869 kshitij.so 45
 
16095 kshitij.so 46
 
15869 kshitij.so 47
class __ProductInfo:
48
 
49
    def __init__(self, identifier, rank, url, available_price, in_stock, codAvailable, source_product_name, thumbnail, coupon):
50
        self.identifier = identifier
51
        self.rank  = rank
52
        self.url = url
53
        self.available_price = available_price
54
        self.in_stock = in_stock
55
        self.codAvailable = codAvailable
56
        self.source_product_name = source_product_name
57
        self.thumbnail = thumbnail
16095 kshitij.so 58
        self.coupon = coupon
15869 kshitij.so 59
 
16095 kshitij.so 60
class __NewBundled:
61
    def __init__(self, newProduct, oldProduct):
62
        self.newProduct = newProduct
63
        self.oldProduct = oldProduct
64
 
15869 kshitij.so 65
def get_mongo_connection(host=options.mongoHost, port=27017):
66
    global con
67
    if con is None:
68
        print "Establishing connection %s host and port %d" %(host,port)
69
        try:
70
            con = pymongo.MongoClient(host, port)
71
        except Exception, e:
72
            print e
73
            return None
74
    return con
75
 
19189 kshitij.so 76
def getNetPriceForItem(itemId, source_id, category_id ,price):
77
    cash_back_type = 0
78
    cash_back = 0
79
    try:
80
        cashBack = getCashBack(itemId, source_id, category_id, mc, options.mongoHost)
81
        if not cashBack or cashBack.get('cash_back_status')!=1:
82
            cash_back_type = 0
83
            cash_back = 0 
84
 
85
        else:
86
            if cashBack['cash_back_type'] in (1,2):
87
 
88
                if cashBack.get('maxCashBack') is not None:
89
 
90
                    if cashBack.get('cash_back_type') ==1 and (float(cashBack.get('cash_back'))*price)/100 > cashBack.get('maxCashBack'):
91
                        cashBack['cash_back_type'] = 2
92
                        cashBack['cash_back'] = cashBack['maxCashBack']
93
                    elif cashBack.get('cash_back_type') ==2 and cashBack.get('cash_back') > cashBack.get('maxCashBack'):
94
                        cashBack['cash_back'] = cashBack['maxCashBack']
95
                    else:
96
                        pass
97
 
98
 
99
 
100
                cash_back_type = cashBack['cash_back_type']
101
                cash_back = float(cashBack['cash_back'])
102
    except Exception as cashBackEx:
103
        pass
104
 
105
    if cash_back_type ==1:
106
        return (price - float(cash_back)*price/100)
107
    elif cash_back_type ==2:
108
        return (price - cash_back)
109
    else:
110
        return price
111
 
112
 
15869 kshitij.so 113
def getSoupObject(url):
114
    print "Getting soup object for"
115
    print url
116
    global RETRY_COUNT
117
    RETRY_COUNT = 1 
118
    while RETRY_COUNT < 10:
119
        try:
120
            soup = None
16019 kshitij.so 121
            request = urllib2.Request(url, headers=headers)
15869 kshitij.so 122
            response = urllib2.urlopen(request)   
123
            response_data = response.read()
124
            response.close()
125
            try:
126
                page=response_data.decode("utf-8")
127
                soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES)
128
            except:
16019 kshitij.so 129
                print traceback.print_exc()
15869 kshitij.so 130
                soup = BeautifulSoup(response_data,convertEntities=BeautifulSoup.HTML_ENTITIES)
131
            if soup is None:
132
                raise
133
            return soup
134
        except Exception as e:
16019 kshitij.so 135
            traceback.print_exc()
15869 kshitij.so 136
            print "Retrying"
137
            RETRY_COUNT = RETRY_COUNT + 1
138
 
139
 
140
def scrapeBestSellers():
141
    global bestSellers
16095 kshitij.so 142
    global exceptionList
15869 kshitij.so 143
    bestSellers = []
144
    rank = 0
145
    page = 1
146
    while (True):
147
        url = (baseUrl)%(page,page-1)
148
        soup = getSoupObject(url)
149
        productDivs = soup.findAll('div',{'class':'pd-list-cont'})
150
        if productDivs is None or len(productDivs)==0:
151
            return
152
        for productDiv in productDivs:
153
            rank = rank + 1
154
            info_tag =  productDiv.find('a')
155
            link = info_tag['href']
156
            scin = info_tag['data-id'].strip()
157
            print link
158
            print scin
15895 kshitij.so 159
            productName = productDiv.find('div',{'class':'pdt-name'}).string
160
            try:
161
                productInfo = sc.read(link)
162
            except Exception as e:
163
                traceback.print_exc()
164
                continue
15869 kshitij.so 165
            product = list(get_mongo_connection().Catalog.MasterData.find({'source_id':5,'identifier':scin}))
166
            if len(product) > 0:
16505 kshitij.so 167
                if product[0].get('ignorePricing') ==1:
168
                    continue
16019 kshitij.so 169
                if productInfo['inStock'] ==1:
19189 kshitij.so 170
                    netPriceAfterCashBack = getNetPriceForItem(product[0]['_id'], SOURCE_MAP.get('SHOPCLUES.COM'), product[0]['category_id'], productInfo['price'])
16019 kshitij.so 171
                    get_mongo_connection().Catalog.MasterData.update({'_id':product[0]['_id']},{"$set":{'rank':rank, 'available_price':productInfo['price'], \
15895 kshitij.so 172
                                                                                                            'in_stock':productInfo['inStock'], 'codAvailable':productInfo['isCod'], \
16021 kshitij.so 173
                                                                                                            'coupon':productInfo['coupon'], 'updatedOn':to_java_date(datetime.now()),'priceUpdatedOn':to_java_date(datetime.now())}})
19189 kshitij.so 174
                    get_mongo_connection().Catalog.Deals.update({'_id':product[0]['_id']}, {'$set' : {'rank':rank,'available_price':productInfo['price'] , 'in_stock':productInfo['inStock'],'codAvailable':productInfo['isCod'],'netPriceAfterCashBack':netPriceAfterCashBack}})
16019 kshitij.so 175
                else:
19189 kshitij.so 176
                    netPriceAfterCashBack = getNetPriceForItem(product[0]['_id'], SOURCE_MAP.get('SHOPCLUES.COM'), product[0]['category_id'], product[0]['available_price'])
16019 kshitij.so 177
                    get_mongo_connection().Catalog.MasterData.update({'_id':product[0]['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':0,'priceUpdatedOn':to_java_date(datetime.now())}})
19189 kshitij.so 178
                    get_mongo_connection().Catalog.Deals.update({'_id':product[0]['_id']}, {'$set' : {'in_stock':0,'netPriceAfterCashBack':netPriceAfterCashBack}})
16019 kshitij.so 179
 
180
                try:
181
                    recomputeDeal(product[0])
182
                except:
183
                    print "Unable to compute deal for %s"%(product[0]['skuBundleId'])
184
 
15869 kshitij.so 185
            else:
186
                #Lets bundle product by finding similar url pattern
15895 kshitij.so 187
                uri = link.replace('http://m.shopclues.com','').replace(".html","")
188
                try:
189
                    int(uri[uri.rfind('-')+1:])
190
                    uri =  uri[:uri.rfind('-')]
191
                except:
192
                    pass
193
                product = list(get_mongo_connection().Catalog.MasterData.find({'source_id':5,'marketPlaceUrl':{'$regex': uri}}))
16099 kshitij.so 194
                toBundle = __ProductInfo(scin, rank, link, productInfo['price'], productInfo['inStock'],productInfo['isCod'], productName, productInfo['thumbnail'] ,productInfo['coupon'])
15869 kshitij.so 195
                if len(product) > 0:
15895 kshitij.so 196
                    bundleNewProduct(product[0], toBundle)
16028 kshitij.so 197
                    try:
198
                        recomputeDeal(product[0])
199
                    except:
200
                        print "Unable to compute deal for %s"%(product[0]['skuBundleId'])
15895 kshitij.so 201
                else:
202
                    exceptionList.append(toBundle)
15869 kshitij.so 203
        page = page+1
16019 kshitij.so 204
 
205
def populateNegativeDeals():
206
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
207
    mc.set("negative_deals", negativeDeals, 600)
208
 
16505 kshitij.so 209
#def recomputePoints(item, deal):
210
#    try:
211
#        if item.get('available_price') == deal['available_price']:
212
#            print "No need to compute points for %d , as price is still same" %(item['_id'])
213
#            raise
214
#        nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
215
#    except:
216
#        print traceback.print_exc()
217
#        nlcPoints = deal['nlcPoints']
218
#        
219
#    
220
#    bundleDealPoints = list(get_mongo_connection().Catalog.DealPoints.find({'skuBundleId':item['skuBundleId'],'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())}}))
221
#    if len(bundleDealPoints) > 0:
222
#        item['manualDealThresholdPrice'] = bundleDealPoints[0]['dealThresholdPrice']
223
#        dealPoints = bundleDealPoints[0]['dealPoints']
224
#    else:
225
#        dealPoints = 0
226
#        item['manualDealThresholdPrice'] = None    
227
#    
228
#    get_mongo_connection().Catalog.Deals.update({'_id':deal['_id']},{"$set":{'totalPoints':deal['totalPoints'] - deal['nlcPoints'] + nlcPoints - deal['dealPoints'] +dealPoints , 'nlcPoints': nlcPoints, 'dealPoints': dealPoints, 'manualDealThresholdPrice': item['manualDealThresholdPrice']}})
16019 kshitij.so 229
 
230
 
231
def recomputeDeal(item):
232
    """Lets recompute deal for this bundle"""
233
    print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
234
    skuBundleId = item['skuBundleId']
19189 kshitij.so 235
 
236
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('netPriceAfterCashBack',pymongo.ASCENDING)]))
16019 kshitij.so 237
    bestPrice = float("inf")
238
    bestOne = None
239
    bestSellerPoints = 0
240
    toUpdate = []
241
    prepaidBestPrice = float("inf")
242
    prepaidBestOne = None
243
    prepaidBestSellerPoints = 0
244
    for similarItem in similarItems:
245
        if similarItem['codAvailable'] ==1:
246
            if mc.get("negative_deals") is None:
247
                populateNegativeDeals()
16181 kshitij.so 248
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
16019 kshitij.so 249
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
250
                continue
251
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
252
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
253
                continue
19189 kshitij.so 254
            if similarItem.get('netPriceAfterCashBack') < bestPrice:
16019 kshitij.so 255
                bestOne = similarItem
19189 kshitij.so 256
                bestPrice = similarItem.get('netPriceAfterCashBack')
16019 kshitij.so 257
                bestSellerPoints = similarItem['bestSellerPoints']
20347 kshitij.so 258
            elif similarItem.get('netPriceAfterCashBack') == bestPrice:
259
 
260
                try:
261
                    if (DEAL_PRIORITY.index(int(similarItem['source_id'])) > DEAL_PRIORITY.index(int(bestOne['source_id']))):
262
                        continue
263
                except:
264
                    traceback.print_exc()
265
 
16019 kshitij.so 266
                bestOne = similarItem
19189 kshitij.so 267
                bestPrice = similarItem.get('netPriceAfterCashBack')
16019 kshitij.so 268
                bestSellerPoints = similarItem['bestSellerPoints']
269
            else:
270
                pass
271
        else:
272
            if mc.get("negative_deals") is None:
273
                populateNegativeDeals()
16181 kshitij.so 274
            if similarItem['in_stock'] == 0  or similarItem['_id'] in mc.get("negative_deals"):
16019 kshitij.so 275
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
276
                continue
277
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
278
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
279
                continue
19189 kshitij.so 280
            if similarItem.get('netPriceAfterCashBack') < prepaidBestPrice:
16019 kshitij.so 281
                prepaidBestOne = similarItem
19189 kshitij.so 282
                prepaidBestPrice = similarItem.get('netPriceAfterCashBack')
16019 kshitij.so 283
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
20347 kshitij.so 284
            elif similarItem.get('netPriceAfterCashBack') == prepaidBestPrice:
285
 
286
                try:
287
                    if (DEAL_PRIORITY.index(int(similarItem['source_id'])) > DEAL_PRIORITY.index(int(bestOne['source_id']))):
288
                        continue
289
                except:
290
                    traceback.print_exc()
291
 
16019 kshitij.so 292
                prepaidBestOne = similarItem
19189 kshitij.so 293
                prepaidBestPrice = similarItem.get('netPriceAfterCashBack')
16019 kshitij.so 294
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
295
            else:
296
                pass
16026 kshitij.so 297
    if bestOne is not None or prepaidBestOne is not None:
16019 kshitij.so 298
        for similarItem in similarItems:
299
            toUpdate.append(similarItem['_id'])
16026 kshitij.so 300
        if bestOne is not None:
301
            toUpdate.remove(bestOne['_id'])
302
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
303
        if prepaidBestOne is not None:
16076 kshitij.so 304
            if bestOne is not None:
19189 kshitij.so 305
                if prepaidBestOne.get('netPriceAfterCashBack') < bestOne.get('netPriceAfterCashBack'): 
16076 kshitij.so 306
                    toUpdate.remove(prepaidBestOne['_id'])
307
                    get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
308
            else:
309
                toUpdate.remove(prepaidBestOne['_id'])
310
                get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
16019 kshitij.so 311
    if len(toUpdate) > 0:
312
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
313
 
19189 kshitij.so 314
 
315
 
15869 kshitij.so 316
 
317
def bundleNewProduct(existingProduct, toBundle):
16095 kshitij.so 318
    global bundledProducts
319
    global exceptionList
15895 kshitij.so 320
    print "Adding new product"
321
    try:
322
        max_id = list(get_mongo_connection().Catalog.MasterData.find().sort([('_id',pymongo.DESCENDING)]).limit(1))
323
        existingProduct['_id'] = max_id[0]['_id'] + 1
324
        existingProduct['addedOn'] = to_java_date(datetime.now())
325
        existingProduct['available_price'] = toBundle.available_price
326
        existingProduct['updatedOn'] = to_java_date(datetime.now())
327
        existingProduct['codAvailable'] = toBundle.codAvailable
16095 kshitij.so 328
        existingProduct['coupon'] = str(toBundle.coupon)
329
        existingProduct['identifier'] = str(toBundle.identifier)
15895 kshitij.so 330
        existingProduct['in_stock'] = toBundle.in_stock
331
        existingProduct['marketPlaceUrl'] = toBundle.url
332
        existingProduct['rank'] = toBundle.rank
333
        existingProduct['source_product_name'] = toBundle.source_product_name
334
        existingProduct['url'] = toBundle.url
17747 kshitij.so 335
        existingProduct['showVideo'] = 0
336
        existingProduct['shippingCost'] = 0
337
        existingProduct['quantity'] = 1
338
        existingProduct['videoLink'] = ""
19189 kshitij.so 339
        existingProduct['showNetPrice'] = 0
15895 kshitij.so 340
        get_mongo_connection().Catalog.MasterData.insert(existingProduct)
16095 kshitij.so 341
        newBundled = __NewBundled(toBundle, existingProduct)
342
        bundledProducts.append(newBundled)
15895 kshitij.so 343
        return {1:'Data added successfully.'}
344
    except Exception as e:
345
        print e
16095 kshitij.so 346
        exceptionList.append(toBundle)
15895 kshitij.so 347
        return {0:'Unable to add data.'}
15869 kshitij.so 348
 
16095 kshitij.so 349
def sendMail():
350
    message="""<html>
351
            <body>
352
            <h3>ShopClues Best Sellers Auto Bundled</h3>
353
            <table border="1" style="width:100%;">
354
            <thead>
355
            <tr>
356
            <th>Item Id</th>
357
            <th>Identifier</th>
358
            <th>Rank</th>
359
            <th>Product Name</th>
360
            <th>Bundle Id</th>
361
            <th>Bundled with Brand</th>
362
            <th>Bundled with Product Name</th>
363
            <th>Available_price</th>
364
            <th>In Stock</th>
365
            <th>Coupon</th>
366
            <th>COD Available</th>
367
            </tr></thead>
368
            <tbody>"""
369
    for bundledProduct in bundledProducts:
370
        newProduct = bundledProduct.newProduct
371
        oldProduct = bundledProduct.oldProduct
372
        message+="""<tr>
373
        <td style="text-align:center">"""+str(oldProduct.get('_id'))+"""</td>
374
        <td style="text-align:center">"""+oldProduct.get('identifier')+"""</td>
375
        <td style="text-align:center">"""+str(oldProduct.get('rank'))+"""</td>
376
        <td style="text-align:center">"""+(oldProduct.get('source_product_name'))+"""</td>
377
        <td style="text-align:center">"""+str(oldProduct.get('skuBundleId'))+"""</td>
378
        <td style="text-align:center">"""+(oldProduct.get('brand'))+"""</td>
379
        <td style="text-align:center">"""+(oldProduct.get('product_name'))+"""</td>
380
        <td style="text-align:center">"""+str(oldProduct.get('available_price'))+"""</td>
381
        <td style="text-align:center">"""+str(oldProduct.get('in_stock'))+"""</td>
382
        <td style="text-align:center">"""+str(oldProduct.get('coupon'))+"""</td>
383
        <td style="text-align:center">"""+str(oldProduct.get('codAvailable'))+"""</td>
384
        </tr>"""
385
    message+="""</tbody></table><h3>Items not bundled</h3><table border="1" style="width:100%;">
386
    <tr>
387
    <th>Identifier</th>
388
    <th>Rank</th>
389
    <th>Product Name</th>
390
    <th>Url</th>
391
    <th>Available Price</th>
392
    <th>In Stock</th>
393
    <th>COD Available</th>
394
    <th>Coupon</th>
16099 kshitij.so 395
    <th>Thumbnail</th>
16095 kshitij.so 396
    </tr></thead>
397
    <tbody>"""
398
    for exceptionItem in exceptionList:
399
        message+="""<tr>
400
        <td style="text-align:center">"""+str(exceptionItem.identifier)+"""</td>
401
        <td style="text-align:center">"""+str(exceptionItem.rank)+"""</td>
402
        <td style="text-align:center">"""+(exceptionItem.source_product_name)+"""</td>
403
        <td style="text-align:center">"""+(exceptionItem.url)+"""</td>
404
        <td style="text-align:center">"""+str(exceptionItem.available_price)+"""</td>
405
        <td style="text-align:center">"""+str(exceptionItem.in_stock)+"""</td>
406
        <td style="text-align:center">"""+str(exceptionItem.codAvailable)+"""</td>
407
        <td style="text-align:center">"""+str(exceptionItem.coupon)+"""</td>
16102 kshitij.so 408
        <td style="text-align:left">"""+(exceptionItem.thumbnail)+"""</td>
16095 kshitij.so 409
        </tr>"""
410
    message+="""</tbody></table></body></html>"""
411
    print message
16184 kshitij.so 412
    encoding = chardet.detect(message)
413
    try:
414
        message = message.decode(encoding.get('encoding'))
415
    except:
416
        pass
16182 kshitij.so 417
    #recipients = ['kshitij.sood@saholic.com']
20172 aman.kumar 418
    recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','ritesh.chauhan@saholic.com','khushal.bhatia@saholic.com']
16095 kshitij.so 419
    msg = MIMEMultipart()
420
    msg['Subject'] = "Shopclues Best Sellers" + ' - ' + str(datetime.now())
421
    msg['From'] = ""
422
    msg['To'] = ",".join(recipients)
423
    msg.preamble = "Shopclues Best Sellers" + ' - ' + str(datetime.now())
424
    html_msg = MIMEText(message, 'html')
425
    msg.attach(html_msg)
426
 
427
    smtpServer = smtplib.SMTP('localhost')
428
    smtpServer.set_debuglevel(1)
429
    sender = 'dtr@shop2020.in'
430
    try:
431
        smtpServer.sendmail(sender, recipients, msg.as_string())
432
        print "Successfully sent email"
433
    except:
16101 kshitij.so 434
        traceback.print_exc()
16095 kshitij.so 435
        print "Error: unable to send email."
436
 
16183 kshitij.so 437
def resetRanks():
16103 kshitij.so 438
    get_mongo_connection().Catalog.MasterData.update({'rank':{'$gt':0},'source_id':5},{'$set' : {'rank':0,'updatedOn':to_java_date(now)}}, multi=True)
15895 kshitij.so 439
 
15869 kshitij.so 440
def main():
16103 kshitij.so 441
    if options.reset == 'True':
442
        resetRanks()
15869 kshitij.so 443
    scrapeBestSellers()
16102 kshitij.so 444
    if len(bundledProducts)>0 or len(exceptionList) > 0:
445
        sendMail()
16190 kshitij.so 446
    else:
447
        "print nothing to send"
15869 kshitij.so 448
 
449
if __name__=='__main__':
450
    main()