Subversion Repositories SmartDukaan

Rev

Rev 14181 | Rev 14209 | 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 urllib2
2
import simplejson as json
3
import pymongo
4
from dtr.utils.utils import to_java_date
13917 kshitij.so 5
from datetime import datetime, timedelta
13828 kshitij.so 6
import time
14180 kshitij.so 7
from multiprocessing import Pool as ThreadPool
8
from multiprocessing import cpu_count
13828 kshitij.so 9
 
10
con = None
11
 
12
headers = { 
13
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
14
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
15
            'Accept-Language' : 'en-US,en;q=0.8',                     
16
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
17
        }
18
 
19
def get_mongo_connection(host='localhost', port=27017):
20
    global con
21
    if con is None:
22
        print "Establishing connection %s host and port %d" %(host,port)
23
        try:
24
            con = pymongo.MongoClient(host, port)
25
        except Exception, e:
26
            print e
27
            return None
28
    return con
29
 
14180 kshitij.so 30
def populate():
31
    toScrapMap = {}
14132 kshitij.so 32
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0}}))
33
    for bestSeller in bestSellers: 
34
        snapdealBestSellers = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':3}))
35
        for data in snapdealBestSellers:
14180 kshitij.so 36
            if not toScrapMap.has_key(data['_id']):
37
                toScrapMap[data['_id']] = data
38
    for k, y in toScrapMap.iteritems():
39
        print k,
40
        print '\t',
41
        print y
42
    pool = ThreadPool(cpu_count() *2)
43
    pool.map(updatePrices,toScrapMap.values())
44
    pool.close()
45
    pool.join()
46
    print "joining threads"
47
    print datetime.now()
48
 
49
 
50
def updatePrices(data):
51
    if data['source_id']!=3:
52
        return
53
    print data['identifier']
54
    if data['identifier'] is None or len(data['identifier'].strip())==0:
55
        print "returning"
56
        return
57
 
58
    try:
59
        if data['priceUpdatedOn'] > to_java_date(datetime.now() - timedelta(minutes=5)):
60
            print "sku id is already updated",data['_id'] 
61
            return
62
    except:
63
        pass
64
 
65
    url="http://www.snapdeal.com/acors/json/gvbps?supc=%s&catId=175&sort=sellingPrice"%(data['identifier'].strip())
66
    print url
67
    time.sleep(1)
68
    lowestOfferPrice = 0
69
    instock = 0
70
    req = urllib2.Request(url,headers=headers)
71
    response = urllib2.urlopen(req)
14187 kshitij.so 72
    response.close()
14180 kshitij.so 73
    json_input = response.read()
74
    if len(json_input) > 0:
75
        vendorInfo = json.loads(json_input)
76
        for vendor in vendorInfo:
77
            lowestOfferPrice = float(vendor['sellingPrice'])
14181 kshitij.so 78
            try:
79
                stock = vendor['buyableInventory']
80
            except:
81
                stock = 0
14180 kshitij.so 82
            if stock > 0 and lowestOfferPrice > 0:
83
                instock = 1
84
                break
14181 kshitij.so 85
    else:
86
        lowestOfferPrice = 0
87
        stock = 0
88
        instock = 0
89
 
14180 kshitij.so 90
    print lowestOfferPrice
91
    print instock
92
    print stock
14181 kshitij.so 93
    print "Lowest Offer Price for id %d is %d , stock is %d and stock count is %d" %(data['_id'],lowestOfferPrice,instock,stock)
14180 kshitij.so 94
    print "*************"
95
    if instock  == 1:
96
        get_mongo_connection().Catalog.MasterData.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice,'updatedOn':to_java_date(datetime.now()),'priceUpdatedOn':to_java_date(datetime.now()),'in_stock':instock}}, multi=True)
97
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':instock}}, multi=True)
98
    else:
99
        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)
100
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock}}, multi=True)
101
 
102
    try:
103
        recomputeDeal(data['skuBundleId'])
104
    except:
105
        print "Unable to compute deal for ",data['skuBundleId']
106
 
107
 
13917 kshitij.so 108
def recomputeDeal(skuBundleId):
109
    """Lets recompute deal for this bundle"""
110
    print "Recomputing for bundleId",skuBundleId
111
 
112
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
113
    bestPrice = float("inf")
114
    bestOne = None
115
    bestSellerPoints = 0
116
    toUpdate = []
117
    for similarItem in similarItems:
13974 kshitij.so 118
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price']:
13917 kshitij.so 119
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
120
            continue
121
        if similarItem['available_price'] < bestPrice:
122
            bestOne = similarItem
123
            bestPrice = similarItem['available_price']
124
            bestSellerPoints = similarItem['bestSellerPoints']
125
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
126
            bestOne = similarItem
127
            bestPrice = similarItem['available_price']
128
            bestSellerPoints = similarItem['bestSellerPoints']
129
        else:
130
            pass
131
    if bestOne is not None:
132
        for similarItem in similarItems:
133
            toUpdate.append(similarItem['_id'])
134
        toUpdate.remove(bestOne['_id'])
135
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
136
    if len(toUpdate) > 0:
137
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
138
 
13828 kshitij.so 139
def main():
14180 kshitij.so 140
    populate()
13828 kshitij.so 141
 
142
if __name__=='__main__':
143
    main()