Subversion Repositories SmartDukaan

Rev

Rev 14180 | Rev 14187 | 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)
72
    json_input = response.read()
73
    if len(json_input) > 0:
74
        vendorInfo = json.loads(json_input)
75
        for vendor in vendorInfo:
76
            lowestOfferPrice = float(vendor['sellingPrice'])
14181 kshitij.so 77
            try:
78
                stock = vendor['buyableInventory']
79
            except:
80
                stock = 0
14180 kshitij.so 81
            if stock > 0 and lowestOfferPrice > 0:
82
                instock = 1
83
                break
14181 kshitij.so 84
    else:
85
        lowestOfferPrice = 0
86
        stock = 0
87
        instock = 0
88
 
14180 kshitij.so 89
    print lowestOfferPrice
90
    print instock
91
    print stock
14181 kshitij.so 92
    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 93
    print "*************"
94
    if instock  == 1:
95
        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)
96
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'available_price':lowestOfferPrice , 'in_stock':instock}}, multi=True)
97
    else:
98
        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)
99
        get_mongo_connection().Catalog.Deals.update({'_id':data['_id']}, {'$set' : {'in_stock':instock}}, multi=True)
100
 
101
    try:
102
        recomputeDeal(data['skuBundleId'])
103
    except:
104
        print "Unable to compute deal for ",data['skuBundleId']
105
 
106
 
13917 kshitij.so 107
def recomputeDeal(skuBundleId):
108
    """Lets recompute deal for this bundle"""
109
    print "Recomputing for bundleId",skuBundleId
110
 
111
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
112
    bestPrice = float("inf")
113
    bestOne = None
114
    bestSellerPoints = 0
115
    toUpdate = []
116
    for similarItem in similarItems:
13974 kshitij.so 117
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price']:
13917 kshitij.so 118
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
119
            continue
120
        if similarItem['available_price'] < bestPrice:
121
            bestOne = similarItem
122
            bestPrice = similarItem['available_price']
123
            bestSellerPoints = similarItem['bestSellerPoints']
124
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
125
            bestOne = similarItem
126
            bestPrice = similarItem['available_price']
127
            bestSellerPoints = similarItem['bestSellerPoints']
128
        else:
129
            pass
130
    if bestOne is not None:
131
        for similarItem in similarItems:
132
            toUpdate.append(similarItem['_id'])
133
        toUpdate.remove(bestOne['_id'])
134
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
135
    if len(toUpdate) > 0:
136
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
137
 
13828 kshitij.so 138
def main():
14180 kshitij.so 139
    populate()
13828 kshitij.so 140
 
141
if __name__=='__main__':
142
    main()