Subversion Repositories SmartDukaan

Rev

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