Subversion Repositories SmartDukaan

Rev

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