Subversion Repositories SmartDukaan

Rev

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