Subversion Repositories SmartDukaan

Rev

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