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