Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
13828 kshitij.so 1
import pymongo
2
from dtr.utils.utils import to_java_date
13915 kshitij.so 3
from datetime import datetime, timedelta
13828 kshitij.so 4
from operator import itemgetter
14123 kshitij.so 5
from dtr.utils import FlipkartScraper,NewFlipkartScraper
13828 kshitij.so 6
 
7
con = None
8
scraperFk = FlipkartScraper.FlipkartScraper()
14123 kshitij.so 9
scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
13828 kshitij.so 10
 
11
def get_mongo_connection(host='localhost', port=27017):
12
    global con
13
    if con is None:
14
        print "Establishing connection %s host and port %d" %(host,port)
15
        try:
16
            con = pymongo.MongoClient(host, port)
17
        except Exception, e:
18
            print e
19
            return None
20
    return con
21
 
22
def scrapeFlipkart():
14131 kshitij.so 23
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
24
    for bestSeller in bestSellers: 
25
        flipkartBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':2}))
26
        for data in flipkartBestSellers:
27
            if data['source_id']!=2:
13915 kshitij.so 28
                continue
14131 kshitij.so 29
            inStock = 0
30
            retryCount = 0
31
            print str(data['identifier'])
32
            if data['identifier'] is None or len(data['identifier'].strip())==0:
33
                print "continue"
14123 kshitij.so 34
                continue
35
 
14131 kshitij.so 36
            try:
37
                if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
38
                    print "sku id is already updated",data['_id'] 
39
                    continue
40
            except:
41
                pass
42
 
43
 
44
            lowestSp = 0
45
            inStock = 0
46
            try:
47
                if data['marketPlaceUrl']!="" or data['marketPlaceUrl'] !="http://www.flipkart.com/ps/%s"%(data['identifier']):
48
                    result = scraperProductPage.read(data['marketPlaceUrl'])
49
                    if result.get('lowestSp')!=0:
50
                        lowestSp = result.get('lowestSp')
51
                        inStock = result.get('inStock')
52
            except:
53
                print "Unable to scrape product page ",data['identifier']
54
 
55
 
56
            if lowestSp == 0:
57
                url = "http://www.flipkart.com/ps/%s"%(data['identifier'].strip())
58
                while(retryCount < 3):
59
                    try:
60
                        vendorsData = scraperFk.read(url)
61
                        fetched = True
62
                        break
63
                    except Exception as e:
64
                        print "***Retry count ",retryCount 
65
                        retryCount+=1
66
                        if retryCount == 3:
67
                            fetched = False
68
                        print e
69
                if not fetched:
70
                    print "Unable to fetch data after multiple tries.Continue for ",data['identifier']
71
                    continue
72
 
73
                sortedVendorsData = []
74
                sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
75
                print "data",sortedVendorsData
76
                lowestSp, iterator = (0,)*2
77
                for vData in sortedVendorsData:
78
                    if iterator == 0:
79
                        lowestSp = vData['sellingPrice']
80
                    break
81
                if lowestSp > 0:
82
                    inStock = 1
83
            print lowestSp
84
            print inStock
14123 kshitij.so 85
            if lowestSp > 0:
14131 kshitij.so 86
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp,'updatedOn':to_java_date(datetime.now()),'priceUpdatedOn':to_java_date(datetime.now()),'in_stock':inStock}}, multi=True)
87
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock}}, multi=True)
88
            else:
89
                get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':inStock,'priceUpdatedOn':to_java_date(datetime.now())}}, multi=True)
90
                get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
91
 
92
            try:
93
                recomputeDeal(data['skuBundleId'])
94
            except:
95
                print "Unable to compute deal for ",data['skuBundleId']
13828 kshitij.so 96
 
13915 kshitij.so 97
def recomputeDeal(skuBundleId):
98
    """Lets recompute deal for this bundle"""
99
    print "Recomputing for bundleId",skuBundleId
100
 
101
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
102
    bestPrice = float("inf")
103
    bestOne = None
104
    bestSellerPoints = 0
105
    toUpdate = []
106
    for similarItem in similarItems:
13974 kshitij.so 107
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price']:
13915 kshitij.so 108
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
109
            continue
110
        if similarItem['available_price'] < bestPrice:
111
            bestOne = similarItem
112
            bestPrice = similarItem['available_price']
113
            bestSellerPoints = similarItem['bestSellerPoints']
114
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
115
            bestOne = similarItem
116
            bestPrice = similarItem['available_price']
117
            bestSellerPoints = similarItem['bestSellerPoints']
118
        else:
119
            pass
120
    if bestOne is not None:
121
        for similarItem in similarItems:
122
            toUpdate.append(similarItem['_id'])
123
        toUpdate.remove(bestOne['_id'])
124
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
125
    if len(toUpdate) > 0:
126
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
127
 
13828 kshitij.so 128
def main():
129
    scrapeFlipkart()
130
 
131
if __name__=='__main__':
132
    main()