Subversion Repositories SmartDukaan

Rev

Rev 14379 | Rev 15829 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13754 kshitij.so 1
import urllib2
2
import simplejson as json
3
import pymongo
13828 kshitij.so 4
from dtr.utils.utils import to_java_date
5
from datetime import datetime
14257 kshitij.so 6
import optparse
14379 kshitij.so 7
import smtplib
8
from email.mime.text import MIMEText
9
from email.mime.multipart import MIMEMultipart
13754 kshitij.so 10
 
14257 kshitij.so 11
con = None
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
 
14379 kshitij.so 20
exceptionList = []
21
 
13754 kshitij.so 22
headers = { 
23
           'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
24
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
25
            'Accept-Language' : 'en-US,en;q=0.8',                     
26
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
27
        }
28
 
29
bestSellers = []
13828 kshitij.so 30
now = datetime.now()
15088 kshitij.so 31
BASE_URL = "snapdeal.com/"
13754 kshitij.so 32
 
33
class __RankInfo:
34
 
15088 kshitij.so 35
    def __init__(self, identifier, rank, category, product_name, page_url):
13754 kshitij.so 36
        self.identifier = identifier
37
        self.rank  = rank
14379 kshitij.so 38
        self.category  =category
15088 kshitij.so 39
        self.product_name = product_name
40
        self.page_url = page_url 
13754 kshitij.so 41
 
14257 kshitij.so 42
def get_mongo_connection(host=options.mongoHost, port=27017):
13754 kshitij.so 43
    global con
44
    if con is None:
45
        print "Establishing connection %s host and port %d" %(host,port)
46
        try:
47
            con = pymongo.MongoClient(host, port)
48
        except Exception, e:
49
            print e
50
            return None
51
    return con
52
 
53
def scrapeBestSellerMobiles():
54
    global bestSellers
55
    rank = 1
56
    for z in [0,20,40,60,80]:
57
        url = "http://www.snapdeal.com/acors/json/product/get/search/175/%d/20?q=&sort=bstslr&keyword=&clickSrc=&viewType=List&lang=en&snr=false" %(z)
58
        print url
59
        request = urllib2.Request(url,headers=headers)
60
        response = urllib2.urlopen(request)
61
 
62
        json_input = response.read()
63
        info = json.loads(json_input)
64
        for offer in info['productOfferGroupDtos']:
15088 kshitij.so 65
            #print offer['name']
66
            #print offer['pageUrl']
13754 kshitij.so 67
            for identifiers in offer['offers']:
15088 kshitij.so 68
                r_info = __RankInfo((identifiers['supcs'])[0],rank, None, offer['name'], offer['pageUrl'])
13754 kshitij.so 69
                bestSellers.append(r_info)
70
            rank += 1
71
 
72
def scrapeBestSellerTablets():
73
    global bestSellers
74
    bestSellers = []
75
    rank = 1
76
    for z in [0,20,40,60,80]:
77
        url = "http://www.snapdeal.com/acors/json/product/get/search/133/%d/20?sort=bstslr&keyword=&clickSrc=&viewType=List&lang=en&snr=false" %(z)
78
        print url
79
        request = urllib2.Request(url,headers=headers)
80
        response = urllib2.urlopen(request)
81
 
82
        json_input = response.read()
83
        info = json.loads(json_input)
84
        for offer in info['productOfferGroupDtos']:
85
            for identifiers in offer['offers']:
15088 kshitij.so 86
                r_info = __RankInfo((identifiers['supcs'])[0],rank, None,offer['name'], offer['pageUrl'])
13754 kshitij.so 87
                bestSellers.append(r_info)
88
            rank += 1
89
 
90
def resetRanks(category):
13828 kshitij.so 91
    oldRankedItems = get_mongo_connection().Catalog.MasterData.find({'rank':{'$gt':0},'source_id':3,'category':category})
92
    for item in oldRankedItems:
93
        get_mongo_connection().Catalog.MasterData.update({'_id':item['_id']}, {'$set' : {'rank':0,'updatedOn':to_java_date(now)}}, multi=True)
13754 kshitij.so 94
 
14379 kshitij.so 95
def commitBestSellers(category):
96
    global exceptionList
13754 kshitij.so 97
    print "Rank",
98
    print '\t',
99
    print 'Identifier'
100
    for x in bestSellers:
101
        print x.rank,
102
        print '\t',
103
        print x.identifier,
104
        col = get_mongo_connection().Catalog.MasterData.find({'identifier':x.identifier.strip()})
105
        print "count sku",
106
        print '\t',
14379 kshitij.so 107
        if len(list(col)) == 0:
108
            x.category = category
109
            exceptionList.append(x)
110
        else:
111
            get_mongo_connection().Catalog.MasterData.update({'identifier':x.identifier.strip()}, {'$set' : {'rank':x.rank,'updatedOn':to_java_date(now)}}, multi=True)
13754 kshitij.so 112
 
14379 kshitij.so 113
def sendEmail():
114
    message="""<html>
115
            <body>
116
            <h3>Snapdeal Best Sellers not in master</h3>
117
            <table border="1" style="width:100%;">
118
            <thead>
119
            <tr><th>Identifier</th>
120
            <th>Category</th>
121
            <th>Rank</th>
15088 kshitij.so 122
            <th>Product Name</th>
123
            <th>Page Url</th>
14379 kshitij.so 124
            </tr></thead>
125
            <tbody>"""
126
    for item in exceptionList:
127
        message+="""<tr>
128
        <td style="text-align:center">"""+(item.identifier)+"""</td>
129
        <td style="text-align:center">"""+(item.category)+"""</td>
130
        <td style="text-align:center">"""+str(item.rank)+"""</td>
15088 kshitij.so 131
        <td style="text-align:center">"""+str(item.product_name)+"""</td>
132
        <td style="text-align:center">"""+str(BASE_URL+item.page_url)+"""</td>
14379 kshitij.so 133
        </tr>"""
134
    message+="""</tbody></table></body></html>"""
135
    print message
136
    #recipients = ['kshitij.sood@saholic.com']
137
    recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','chaitnaya.vats@saholic.com','manoj.kumar@saholic.com']
138
    msg = MIMEMultipart()
139
    msg['Subject'] = "Snapdeal Best Sellers" + ' - ' + str(datetime.now())
140
    msg['From'] = ""
141
    msg['To'] = ",".join(recipients)
142
    msg.preamble = "Snapdeal Best Sellers" + ' - ' + str(datetime.now())
143
    html_msg = MIMEText(message, 'html')
144
    msg.attach(html_msg)
145
 
146
    smtpServer = smtplib.SMTP('localhost')
147
    smtpServer.set_debuglevel(1)
148
    sender = 'dtr@shop2020.in'
149
    try:
150
        smtpServer.sendmail(sender, recipients, msg.as_string())
151
        print "Successfully sent email"
152
    except:
153
        print "Error: unable to send email."
154
 
155
 
156
 
13754 kshitij.so 157
def main():
158
    scrapeBestSellerMobiles()
159
    if len(bestSellers) > 0:
160
        resetRanks('Mobiles')
14379 kshitij.so 161
        commitBestSellers('Mobiles')
13754 kshitij.so 162
    scrapeBestSellerTablets()
163
    if len(bestSellers) > 0:
164
        resetRanks('Tablets')
14379 kshitij.so 165
        commitBestSellers('Tablets')
166
 
167
    sendEmail()
13754 kshitij.so 168
 
169
if __name__=='__main__':
170
    main()