Subversion Repositories SmartDukaan

Rev

Rev 14329 | Rev 15269 | 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
14178 kshitij.so 6
from multiprocessing import Pool as ThreadPool
14172 kshitij.so 7
from multiprocessing import cpu_count
14255 kshitij.so 8
import optparse
14325 kshitij.so 9
from dtr.storage.MemCache import MemCache
14705 kshitij.so 10
from dtr.utils.utils import getCashBack
13828 kshitij.so 11
 
12
con = None
13
 
14255 kshitij.so 14
parser = optparse.OptionParser()
15
parser.add_option("-m", "--m", dest="mongoHost",
16
                      default="localhost",
17
                      type="string", help="The HOST where the mongo server is running",
18
                      metavar="mongo_host")
19
 
20
(options, args) = parser.parse_args()
21
 
14325 kshitij.so 22
mc = MemCache(options.mongoHost)
23
 
14255 kshitij.so 24
def get_mongo_connection(host=options.mongoHost, port=27017):
13828 kshitij.so 25
    global con
26
    if con is None:
27
        print "Establishing connection %s host and port %d" %(host,port)
28
        try:
29
            con = pymongo.MongoClient(host, port)
30
        except Exception, e:
31
            print e
32
            return None
33
    return con
34
 
14149 kshitij.so 35
def populate():
36
    toScrapMap = {}
14131 kshitij.so 37
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
38
    for bestSeller in bestSellers: 
14149 kshitij.so 39
        amazonBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':2}))
40
        for data in amazonBestSellers:
41
            if not toScrapMap.has_key(data['_id']):
42
                toScrapMap[data['_id']] = data
14251 kshitij.so 43
    dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':2,'showDeal':1,'totalPoints':{'$gt':0}}))
44
    for deal in dealFlagged:
45
        if not toScrapMap.has_key(deal['_id']):
14262 kshitij.so 46
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
47
            toScrapMap[deal['_id']] = data[0]
14178 kshitij.so 48
    pool = ThreadPool(cpu_count() *2)
14149 kshitij.so 49
    pool.map(scrapeFlipkart,toScrapMap.values())
50
    pool.close()
51
    pool.join()
14251 kshitij.so 52
    print "joining threads at %s"%(str(datetime.now()))
14149 kshitij.so 53
 
54
def scrapeFlipkart(data):
55
    if data['source_id']!=2:
14157 kshitij.so 56
        return
14149 kshitij.so 57
    retryCount = 0
58
    print str(data['identifier'])
59
    if data['identifier'] is None or len(data['identifier'].strip())==0:
14157 kshitij.so 60
        print "returning in valid identifier"
61
        return
14149 kshitij.so 62
 
63
    try:
64
        if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
65
            print "sku id is already updated",data['_id'] 
14157 kshitij.so 66
            return
14149 kshitij.so 67
    except:
68
        pass
69
 
70
 
71
    lowestSp = 0
72
    inStock = 0
14157 kshitij.so 73
    scraperFk = FlipkartScraper.FlipkartScraper()
74
    scraperProductPage = NewFlipkartScraper.FlipkartProductPageScraper()
14149 kshitij.so 75
    try:
76
        if data['marketPlaceUrl']!="" or data['marketPlaceUrl'] !="http://www.flipkart.com/ps/%s"%(data['identifier']):
77
            result = scraperProductPage.read(data['marketPlaceUrl'])
78
            if result.get('lowestSp')!=0:
79
                lowestSp = result.get('lowestSp')
80
                inStock = result.get('inStock')
81
    except:
82
        print "Unable to scrape product page ",data['identifier']
83
 
84
 
85
    if lowestSp == 0:
86
        url = "http://www.flipkart.com/ps/%s"%(data['identifier'].strip())
87
        while(retryCount < 3):
14131 kshitij.so 88
            try:
14149 kshitij.so 89
                vendorsData = scraperFk.read(url)
90
                fetched = True
91
                break
92
            except Exception as e:
93
                print "***Retry count ",retryCount 
94
                retryCount+=1
95
                if retryCount == 3:
96
                    fetched = False
97
                print e
98
        if not fetched:
99
            print "Unable to fetch data after multiple tries.Continue for ",data['identifier']
14157 kshitij.so 100
            return
14149 kshitij.so 101
 
102
        sortedVendorsData = []
103
        sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
104
        print "data",sortedVendorsData
105
        lowestSp, iterator = (0,)*2
106
        for vData in sortedVendorsData:
107
            if iterator == 0:
108
                lowestSp = vData['sellingPrice']
109
            break
110
        if lowestSp > 0:
111
            inStock = 1
112
    print lowestSp
113
    print inStock
114
    if lowestSp > 0:
115
        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)
116
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestSp , 'in_stock':inStock}}, multi=True)
117
    else:
118
        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)
119
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':inStock}}, multi=True)
120
 
121
    try:
122
        recomputeDeal(data['skuBundleId'])
123
    except:
124
        print "Unable to compute deal for ",data['skuBundleId']
13828 kshitij.so 125
 
14325 kshitij.so 126
def populateNegativeDeals():
127
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
128
    mc.set("negative_deals", negativeDeals, 600)  
129
 
13915 kshitij.so 130
def recomputeDeal(skuBundleId):
131
    """Lets recompute deal for this bundle"""
132
    print "Recomputing for bundleId",skuBundleId
133
 
134
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
135
    bestPrice = float("inf")
136
    bestOne = None
137
    bestSellerPoints = 0
138
    toUpdate = []
139
    for similarItem in similarItems:
14329 kshitij.so 140
        if mc.get("negative_deals") is None:
14325 kshitij.so 141
            populateNegativeDeals()
14705 kshitij.so 142
        try:
143
            cashBack = getCashBack(similarItem['_id'], similarItem['source_id'], similarItem['category_id'], mc, options.mongoHost)
144
            if not cashBack or cashBack.get('cash_back_status')!=1:
145
                pass
146
            else:
147
                if cashBack['cash_back_type'] ==1:
148
                    similarItem['available_price'] = similarItem['available_price'] - similarItem['available_price'] * float(cashBack['cash_back'])/100
149
                elif cashBack['cash_back_type'] ==2:
150
                    similarItem['available_price'] = similarItem['available_price'] - float(cashBack['cash_back'])
151
                else:
152
                    pass
153
        except Exception as cashBackEx:
154
            print cashBackEx
155
            print "Error calculating cashback."
14329 kshitij.so 156
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
13915 kshitij.so 157
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
158
            continue
159
        if similarItem['available_price'] < bestPrice:
160
            bestOne = similarItem
161
            bestPrice = similarItem['available_price']
162
            bestSellerPoints = similarItem['bestSellerPoints']
163
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
164
            bestOne = similarItem
165
            bestPrice = similarItem['available_price']
166
            bestSellerPoints = similarItem['bestSellerPoints']
167
        else:
168
            pass
169
    if bestOne is not None:
170
        for similarItem in similarItems:
171
            toUpdate.append(similarItem['_id'])
172
        toUpdate.remove(bestOne['_id'])
173
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
174
    if len(toUpdate) > 0:
175
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
176
 
13828 kshitij.so 177
def main():
14157 kshitij.so 178
    populate()
13828 kshitij.so 179
 
180
if __name__=='__main__':
181
    main()