| 15509 |
manish.sha |
1 |
'''
|
|
|
2 |
Created on Jan 15, 2015
|
|
|
3 |
|
|
|
4 |
@author: Manish
|
|
|
5 |
'''
|
|
|
6 |
from bs4 import BeautifulSoup
|
|
|
7 |
from bson.binary import Binary
|
|
|
8 |
from datetime import datetime, date, timedelta
|
|
|
9 |
from dtr import main
|
| 15791 |
manish.sha |
10 |
from dtr.dao import AffiliateInfo, Order, SubOrder, ShopCluesAffiliateInfo
|
| 15509 |
manish.sha |
11 |
from dtr.main import getBrowserObject, ScrapeException, getStore, ParseException, \
|
|
|
12 |
Store as MStore, ungzipResponse, tprint
|
|
|
13 |
from dtr.storage import Mongo
|
|
|
14 |
from dtr.storage.Mongo import getImgSrc
|
|
|
15 |
from dtr.utils.utils import fetchResponseUsingProxy
|
|
|
16 |
from pprint import pprint
|
|
|
17 |
from pymongo import MongoClient
|
|
|
18 |
import json
|
|
|
19 |
import pymongo
|
|
|
20 |
import re
|
|
|
21 |
import time
|
|
|
22 |
import traceback
|
|
|
23 |
import urllib
|
| 15791 |
manish.sha |
24 |
import urllib2
|
| 15509 |
manish.sha |
25 |
from urlparse import urlparse, parse_qs
|
| 15791 |
manish.sha |
26 |
import xml.etree.ElementTree as ET
|
|
|
27 |
from dtr.storage import MemCache
|
| 16097 |
manish.sha |
28 |
from dtr.storage.Mongo import getDealRank
|
| 15509 |
manish.sha |
29 |
|
|
|
30 |
USERNAME='profittill2@gmail.com'
|
|
|
31 |
PASSWORD='spice@2020'
|
| 15791 |
manish.sha |
32 |
AFFLIATE_TRASACTIONS_URL = "https://admin.optimisemedia.com/v2/reports/affiliate/leads/leadsummaryexport.aspx?Contact=796881&Country=26&Agency=95&Merchant=420562&Status=-1&Year=%d&Month=%d&Day=%d&EndYear=%d&EndMonth=%d&EndDay=%d&DateType=0&Sort=CompletionDate&Login=1347562DA5E3EFF6FB1561765C47C782&Format=XML&RestrictURL=0"
|
| 15509 |
manish.sha |
33 |
ORDER_TRACK_URL='http://www.shopclues.com/index.php?dispatch=order_lookup.details'
|
| 15791 |
manish.sha |
34 |
ORDER_TRACK_URL_DB='https://sm.shopclues.com/trackOrder?'
|
| 15509 |
manish.sha |
35 |
BASE_URL= 'http://www.shopclues.com'
|
|
|
36 |
BASE_MURL= 'http://m.shopclues.com'
|
|
|
37 |
|
|
|
38 |
class Store(MStore):
|
|
|
39 |
|
|
|
40 |
'''
|
|
|
41 |
This is to map order statuses of our system to order statuses of snapdeal.
|
|
|
42 |
And our statuses will change accordingly.
|
|
|
43 |
|
|
|
44 |
'''
|
|
|
45 |
OrderStatusMap = {
|
|
|
46 |
MStore.ORDER_PLACED : ['payment successful', 'new order - cod confirmation pending', 'processing', 'quality check','on schedule', 'processing - pickup-initiated', 'processing - ready to dispatch'],
|
|
|
47 |
MStore.ORDER_DELIVERED : ['delivered', 'complete'],
|
|
|
48 |
MStore.ORDER_SHIPPED : ['in transit', 'dispatched','shipped','order handed to courier'],
|
| 16140 |
manish.sha |
49 |
MStore.ORDER_CANCELLED : ['payment failed', 'canceled', 'payment declined', 'order on hold - cancellation requested by customer', 'courier returned', 'canceled on customer request']
|
| 15509 |
manish.sha |
50 |
}
|
|
|
51 |
OrderStatusConfirmationMap= {
|
| 15791 |
manish.sha |
52 |
"P" : "Payment Successful",
|
|
|
53 |
"D" : "Order Declined",
|
|
|
54 |
"O" : "New Order - COD confirmation Pending"
|
| 15509 |
manish.sha |
55 |
}
|
|
|
56 |
|
|
|
57 |
CONF_CB_AMOUNT = MStore.CONF_CB_DISCOUNTED_PRICE
|
|
|
58 |
|
| 16111 |
manish.sha |
59 |
def __init__(self,store_id):
|
|
|
60 |
super(Store, self).__init__(store_id)
|
|
|
61 |
|
| 15791 |
manish.sha |
62 |
def convertToObj(self,offer):
|
|
|
63 |
orderRef = offer['TransactionId']
|
|
|
64 |
orderRef = orderRef[0:len(orderRef)-10]
|
|
|
65 |
offer1 = ShopCluesAffiliateInfo(offer['UID'], offer['TransactionTime'], offer['TransactionId'], orderRef, offer['MerchantRef'], offer['Merchant'], offer['PID'], offer['Product'], float(str(offer['SR'])), float(str(offer['TransactionValue'])), offer['UKey'], offer['ClickTime'], offer['Status'])
|
|
|
66 |
return offer1
|
|
|
67 |
|
|
|
68 |
def _saveToAffiliate(self, offers):
|
|
|
69 |
collection = self.db.shopcluesOrderAffiliateInfo
|
|
|
70 |
mcollection = self.db.merchantOrder
|
|
|
71 |
for offerObj in offers:
|
|
|
72 |
offer = self.convertToObj(offerObj)
|
|
|
73 |
collection.update({"transactionId":offer.transactionId, "subTagId":offer.subTagId, "payOut":offer.payOut},{"$set":todict(offer)}, upsert=True)
|
|
|
74 |
mcollection.update({"subTagId":offer.subTagId, "storeId":self.store_id, "subOrders.missingAff":True}, {"$set":{"subOrders.$.missingAff":False}})
|
|
|
75 |
|
| 15940 |
manish.sha |
76 |
def scrapeAffiliate(self, startDate=datetime.today() - timedelta(days=10), endDate=datetime.today()):
|
| 15791 |
manish.sha |
77 |
uri = AFFLIATE_TRASACTIONS_URL%(startDate.year,startDate.month,startDate.day,endDate.year,endDate.month,endDate.day)
|
|
|
78 |
root = ET.parse(urllib2.urlopen(uri)).getroot()
|
|
|
79 |
if len(root)> 0 and len(root[0])> 0:
|
|
|
80 |
offers = []
|
|
|
81 |
for child in root[0][0]:
|
|
|
82 |
offers.append(child.attrib)
|
|
|
83 |
self._saveToAffiliate(offers)
|
|
|
84 |
|
| 15509 |
manish.sha |
85 |
def _setLastSaleDate(self, saleDate):
|
|
|
86 |
self.db.lastSaleDtate.update({'storeId':self.store_id}, {'$set':{'saleDate':saleDate}})
|
|
|
87 |
|
|
|
88 |
def getName(self):
|
|
|
89 |
return "shopclues"
|
|
|
90 |
|
|
|
91 |
def _getLastSaleDate(self,):
|
|
|
92 |
lastDaySaleObj = self.db.lastDaySale.find_one({"storeId":self.store_id})
|
|
|
93 |
if lastDaySaleObj is None:
|
|
|
94 |
return datetime.min
|
|
|
95 |
|
|
|
96 |
def _getStatusFromDetailedStatus(self, detailedStatus):
|
|
|
97 |
for key, value in Store.OrderStatusMap.iteritems():
|
|
|
98 |
if detailedStatus.lower() in value:
|
|
|
99 |
return key
|
|
|
100 |
print "Detailed Status need to be mapped", detailedStatus, self.store_id
|
|
|
101 |
return None
|
|
|
102 |
|
| 15791 |
manish.sha |
103 |
def _getSingleSubOrderMap(self, orderId, soup, orderObj):
|
|
|
104 |
orderStatus = self.OrderStatusConfirmationMap.get(orderObj['0']['status'])
|
|
|
105 |
statusTime= soup.findAll(attrs={'class' : 'sts no_mobile'})[1].contents[2].strip()
|
| 15509 |
manish.sha |
106 |
productDetailsMap = {}
|
|
|
107 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 15791 |
manish.sha |
108 |
firstRow = orderTable.pop(0)
|
| 15949 |
manish.sha |
109 |
totalColumns = len(firstRow.find_all('th'))
|
| 15791 |
manish.sha |
110 |
jsonSubOrdersMap = {}
|
|
|
111 |
count = 1
|
|
|
112 |
|
|
|
113 |
for val in orderObj['0']['items'].values():
|
|
|
114 |
newCount = 0
|
| 16110 |
manish.sha |
115 |
counts = []
|
| 15791 |
manish.sha |
116 |
for key in jsonSubOrdersMap.keys():
|
|
|
117 |
splitKey = key.split('-')
|
| 16112 |
manish.sha |
118 |
if orderObj['0']['is_parent_order'] == 'N':
|
|
|
119 |
if str(val['order_id']) == splitKey[0]:
|
|
|
120 |
counts.append(int(splitKey[1]))
|
|
|
121 |
else:
|
|
|
122 |
if str(val['child']) == splitKey[0]:
|
|
|
123 |
counts.append(int(splitKey[1]))
|
| 16110 |
manish.sha |
124 |
|
|
|
125 |
if len(counts) >0:
|
|
|
126 |
newCount = max(counts)
|
| 16108 |
manish.sha |
127 |
count = newCount +1
|
| 16112 |
manish.sha |
128 |
if orderObj['0']['is_parent_order'] == 'N':
|
|
|
129 |
jsonSubOrdersMap[str(val['order_id'])+'-'+str(count)] = val
|
|
|
130 |
else:
|
|
|
131 |
jsonSubOrdersMap[str(val['child'])+'-'+str(count)] = val
|
| 15791 |
manish.sha |
132 |
|
| 16110 |
manish.sha |
133 |
|
| 15941 |
manish.sha |
134 |
print jsonSubOrdersMap.items()
|
|
|
135 |
|
| 15791 |
manish.sha |
136 |
count = 1
|
| 15509 |
manish.sha |
137 |
for orderTr in orderTable:
|
| 15791 |
manish.sha |
138 |
productDetailsSubMap = None
|
|
|
139 |
productDetailsSubMap = {}
|
| 15509 |
manish.sha |
140 |
cols = orderTr.find_all('td')
|
|
|
141 |
product_details = cols[0].find_all('a')
|
|
|
142 |
#print product_details
|
|
|
143 |
productUrl = product_details[0].get('href')
|
|
|
144 |
productName = product_details[0].contents[0].strip()
|
|
|
145 |
quantity = int(cols[1].text.strip())
|
| 15980 |
manish.sha |
146 |
sellingPrice = long(cols[2].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
147 |
discount = 0
|
|
|
148 |
subtotal = 0
|
|
|
149 |
if totalColumns == 5:
|
| 15949 |
manish.sha |
150 |
if cols[3].text.strip()!='-' and 'Rs.' in cols[3].text.strip():
|
| 15980 |
manish.sha |
151 |
discount = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
152 |
else:
|
|
|
153 |
discount = 0
|
| 15980 |
manish.sha |
154 |
subtotal = long(cols[4].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
155 |
else:
|
| 15980 |
manish.sha |
156 |
subtotal = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15509 |
manish.sha |
157 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
|
|
158 |
productDetailsSubMap['productName']=productName
|
| 15791 |
manish.sha |
159 |
productDetailsSubMap['subOrderTrackingUrl']=ORDER_TRACK_URL_DB+'order_id=' +str(orderId)+'&email_id='+ orderObj['0']['email']
|
| 15509 |
manish.sha |
160 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
|
|
161 |
productDetailsSubMap['quantity']=quantity
|
|
|
162 |
productDetailsSubMap['discount']=discount
|
|
|
163 |
productDetailsSubMap['subtotal']=subtotal
|
| 15942 |
manish.sha |
164 |
key = str(orderId)+'-'+str(count)
|
|
|
165 |
print 'SubOrder Map Key--',key
|
| 15791 |
manish.sha |
166 |
jsonSubOrderDetails = jsonSubOrdersMap.get(str(orderId)+'-'+str(count))
|
|
|
167 |
productCode = jsonSubOrderDetails['product_code']
|
|
|
168 |
productImgUrl = jsonSubOrderDetails['images']['image_path'][0]
|
| 15509 |
manish.sha |
169 |
productDetailsSubMap['productCode']=productCode
|
|
|
170 |
productDetailsSubMap['imgUrl']=productImgUrl
|
|
|
171 |
|
| 15791 |
manish.sha |
172 |
productDetailsSubMap['subOrderStatus']=orderStatus
|
|
|
173 |
productDetailsSubMap['subOrderStatusTime']=statusTime
|
|
|
174 |
productDetailsMap[str(orderId)+'-'+str(count)]=productDetailsSubMap
|
|
|
175 |
count = count +1
|
| 15509 |
manish.sha |
176 |
return productDetailsMap
|
|
|
177 |
|
| 15791 |
manish.sha |
178 |
def _getMultiSubOrdersMap(self, orderId, soup, orderObj):
|
| 15509 |
manish.sha |
179 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 16105 |
manish.sha |
180 |
firstRow = orderTable.pop(0)
|
| 15791 |
manish.sha |
181 |
#totalColumns = len(firstRow.find_all('td'))
|
| 15509 |
manish.sha |
182 |
productDetailsMap = {}
|
| 15791 |
manish.sha |
183 |
'''
|
|
|
184 |
jsonSubOrdersMap = {}
|
|
|
185 |
for val in orderObj['0']['items'].values():
|
|
|
186 |
jsonSubOrdersMap[val['order_id']] = val
|
|
|
187 |
'''
|
|
|
188 |
existingOrders = []
|
| 15509 |
manish.sha |
189 |
for orderTr in orderTable:
|
| 15791 |
manish.sha |
190 |
subOrderDetailsMap = {}
|
|
|
191 |
|
| 15509 |
manish.sha |
192 |
cols = orderTr.find_all('td')
|
|
|
193 |
product_details = cols[0].find_all('a')
|
|
|
194 |
#print product_details
|
|
|
195 |
subOrderId= product_details[1].contents[0].strip()
|
| 15791 |
manish.sha |
196 |
if subOrderId in existingOrders:
|
|
|
197 |
continue
|
|
|
198 |
else:
|
|
|
199 |
existingOrders.append(subOrderId)
|
|
|
200 |
#productUrl = product_details[0].get('href')
|
|
|
201 |
#productName = product_details[0].contents[0].strip()
|
|
|
202 |
subOrderTrackingParsingUrl = product_details[1].get('href')
|
|
|
203 |
#subOrderTrackingUrl = subOrderTrackingParsingUrl.split('order_lookup.details&')[1]
|
|
|
204 |
'''
|
| 15509 |
manish.sha |
205 |
quantity = int(cols[1].text.strip())
|
|
|
206 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| 15791 |
manish.sha |
207 |
discount = 0
|
|
|
208 |
subtotal = 0
|
|
|
209 |
if totalColumns == 5:
|
|
|
210 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
|
|
211 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
212 |
else:
|
|
|
213 |
discount = 0
|
|
|
214 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
|
|
215 |
else:
|
|
|
216 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
| 15509 |
manish.sha |
217 |
productDetailsSubMap['productUrl']=BASE_MURL+productUrl
|
|
|
218 |
productDetailsSubMap['productName']=productName
|
| 15791 |
manish.sha |
219 |
productDetailsSubMap['subOrderTrackingUrl']=ORDER_TRACK_URL_DB+subOrderTrackingUrl
|
| 15509 |
manish.sha |
220 |
productDetailsSubMap['sellingPrice']=sellingPrice
|
|
|
221 |
productDetailsSubMap['quantity']=quantity
|
|
|
222 |
productDetailsSubMap['discount']=discount
|
|
|
223 |
productDetailsSubMap['subtotal']=subtotal
|
| 15791 |
manish.sha |
224 |
jsonSubOrderDetails = jsonSubOrdersMap.get(subOrderId)
|
|
|
225 |
productCode = jsonSubOrderDetails['product_code']
|
|
|
226 |
productImgUrl = jsonSubOrderDetails['images']['image_path'][0]
|
| 15509 |
manish.sha |
227 |
productDetailsSubMap['productCode']=productCode
|
|
|
228 |
productDetailsSubMap['imgUrl']=productImgUrl
|
| 15791 |
manish.sha |
229 |
'''
|
| 15509 |
manish.sha |
230 |
br1 = getBrowserObject()
|
| 16106 |
manish.sha |
231 |
orderTrackingPage = br1.open(BASE_URL+subOrderTrackingParsingUrl)
|
| 15509 |
manish.sha |
232 |
headers = str(orderTrackingPage.info()).split('\n')
|
|
|
233 |
orderTrackingPage= ungzipResponse(orderTrackingPage)
|
|
|
234 |
jsonResponse = None
|
|
|
235 |
for header in headers:
|
|
|
236 |
header = header.split(':')
|
|
|
237 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
238 |
jsonResponse = json.loads(orderTrackingPage)
|
|
|
239 |
|
|
|
240 |
orderTrackingPageSoup = None
|
|
|
241 |
if jsonResponse is not None:
|
|
|
242 |
orderTrackingPageSoup = BeautifulSoup(str(jsonResponse['text']))
|
|
|
243 |
else:
|
|
|
244 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
| 15791 |
manish.sha |
245 |
'''
|
| 15509 |
manish.sha |
246 |
subOrderStatusList = orderTrackingPageSoup.findAll(attrs={'class' : 'price ord_status'})
|
|
|
247 |
subOrderStatus = subOrderStatusList[0].contents[0].strip()
|
|
|
248 |
subOrderStatusTime= orderTrackingPageSoup.findAll(attrs={'class' : 'sts no_mobile'})[1].contents[2].strip()
|
|
|
249 |
productDetailsSubMap['subOrderStatus'] = subOrderStatus
|
|
|
250 |
productDetailsSubMap['subOrderStatusTime'] = subOrderStatusTime
|
|
|
251 |
productDetailsSubMap['parentOrderId']=orderId
|
| 15791 |
manish.sha |
252 |
'''
|
|
|
253 |
|
|
|
254 |
subOrderDetailsMap = self._getSingleSubOrderMap(subOrderId, orderTrackingPageSoup, orderObj)
|
| 15509 |
manish.sha |
255 |
|
| 15791 |
manish.sha |
256 |
productDetailsMap = dict(productDetailsMap.items()+subOrderDetailsMap.items())
|
| 15509 |
manish.sha |
257 |
|
|
|
258 |
return productDetailsMap
|
|
|
259 |
|
|
|
260 |
def updateCashbackInSubOrders(self, subOrders):
|
|
|
261 |
for subOrder in subOrders:
|
|
|
262 |
cashbackStatus = Store.CB_NA
|
|
|
263 |
cashbackAmount = 0
|
|
|
264 |
percentage = 0
|
|
|
265 |
amount = subOrder.amountPaid
|
|
|
266 |
if amount > 0:
|
|
|
267 |
(cashbackAmount, percentage) = self.getCashbackAmount(subOrder.productCode, amount)
|
|
|
268 |
if cashbackAmount > 0:
|
|
|
269 |
cashbackStatus = Store.CB_PENDING
|
|
|
270 |
subOrder.cashBackStatus = cashbackStatus
|
|
|
271 |
subOrder.cashBackAmount = cashbackAmount
|
|
|
272 |
subOrder.cashBackPercentage = percentage
|
|
|
273 |
return subOrders
|
|
|
274 |
|
| 15947 |
manish.sha |
275 |
def _parseOrders(self, orderId, mpOrderId, subTagId, userId, page, orderSuccessUrl, orderObj):
|
| 15509 |
manish.sha |
276 |
soup = BeautifulSoup(page)
|
|
|
277 |
productDetailsMap = {}
|
|
|
278 |
paymentFields = soup.findAll(attrs={'class' : 'box_paymentcalculations_row'})
|
|
|
279 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 15948 |
manish.sha |
280 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace("\r","").replace(" ","")
|
| 15509 |
manish.sha |
281 |
ordersubtotal=0
|
|
|
282 |
ordercluebucks=0
|
|
|
283 |
ordershippingcost=0
|
|
|
284 |
ordertotal=0
|
|
|
285 |
|
|
|
286 |
for val in paymentFields:
|
|
|
287 |
for value in val.contents:
|
|
|
288 |
if value is not None:
|
|
|
289 |
if 'div' in str(value).strip():
|
|
|
290 |
if 'Subtotal' in value.text.strip():
|
| 15981 |
manish.sha |
291 |
ordersubtotal = long(val.contents[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15509 |
manish.sha |
292 |
print ordersubtotal
|
|
|
293 |
if 'Shipping Cost' in value.text.strip():
|
| 15981 |
manish.sha |
294 |
ordershippingcost = long(val.contents[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15509 |
manish.sha |
295 |
print ordershippingcost
|
|
|
296 |
if 'Clue' in value.text.strip():
|
| 15981 |
manish.sha |
297 |
ordercluebucks = long(val.contents[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15509 |
manish.sha |
298 |
print ordercluebucks
|
|
|
299 |
if 'Total' in value.text.strip():
|
| 15791 |
manish.sha |
300 |
ordertotal = val.contents[3].text.strip().replace("Rs.","")
|
|
|
301 |
ordertotal = ordertotal.replace(',','')
|
| 15509 |
manish.sha |
302 |
print ordertotal
|
| 15791 |
manish.sha |
303 |
|
|
|
304 |
if orderObj['0']['is_parent_order'] == 'N':
|
| 15947 |
manish.sha |
305 |
productDetailsMap = self._getSingleSubOrderMap(mpOrderId, soup, orderObj)
|
| 15509 |
manish.sha |
306 |
else:
|
| 15947 |
manish.sha |
307 |
productDetailsMap = self._getMultiSubOrdersMap(mpOrderId, soup, orderObj)
|
| 15509 |
manish.sha |
308 |
|
| 15791 |
manish.sha |
309 |
merchantOrder = Order(orderId, userId, subTagId, self.store_id, orderSuccessUrl)
|
| 15509 |
manish.sha |
310 |
merchantOrder.placedOn = placedOn
|
| 15791 |
manish.sha |
311 |
merchantOrder.merchantOrderId = orderObj['0']['order_id']
|
| 15509 |
manish.sha |
312 |
merchantOrder.paidAmount = ordertotal
|
|
|
313 |
totalOrdersAmount = 0
|
|
|
314 |
totalDiscount = 0
|
|
|
315 |
subOrders= []
|
|
|
316 |
for key in productDetailsMap:
|
|
|
317 |
subOrderDetail = productDetailsMap.get(key)
|
|
|
318 |
totalOrdersAmount = totalOrdersAmount + (subOrderDetail['sellingPrice'] * subOrderDetail['quantity'])
|
|
|
319 |
totalDiscount = totalDiscount + (subOrderDetail['discount'] * subOrderDetail['quantity'])
|
|
|
320 |
subOrder = SubOrder(subOrderDetail['productName'], subOrderDetail['productUrl'], placedOn, subOrderDetail['subtotal'])
|
|
|
321 |
subOrder.merchantSubOrderId = key
|
|
|
322 |
subOrder.detailedStatus = subOrderDetail['subOrderStatus']
|
|
|
323 |
subOrder.imgUrl = subOrderDetail['imgUrl']
|
|
|
324 |
subOrder.offerDiscount = subOrderDetail['discount'] * subOrderDetail['quantity']
|
|
|
325 |
subOrder.unitPrice = subOrderDetail['sellingPrice']
|
|
|
326 |
subOrder.productCode = subOrderDetail['productCode']
|
|
|
327 |
subOrder.amountPaid = subOrderDetail['subtotal']
|
|
|
328 |
subOrder.quantity = subOrderDetail['quantity']
|
| 15791 |
manish.sha |
329 |
subOrder.tracingkUrl = subOrderDetail['subOrderTrackingUrl']
|
| 16097 |
manish.sha |
330 |
dealRank = getDealRank(subOrder.productCode, self.store_id, merchantOrder.userId)
|
|
|
331 |
subOrder.dealRank = dealRank.get('rank')
|
|
|
332 |
subOrder.rankDesc = dealRank.get('description')
|
| 15509 |
manish.sha |
333 |
subOrders.append(subOrder)
|
|
|
334 |
print totalOrdersAmount, totalDiscount
|
|
|
335 |
merchantOrder.totalAmount = totalOrdersAmount
|
|
|
336 |
merchantOrder.discountApplied = totalDiscount
|
|
|
337 |
merchantOrder.deliveryCharges = ordershippingcost
|
|
|
338 |
merchantOrder.subOrders = self.updateCashbackInSubOrders(subOrders)
|
|
|
339 |
|
|
|
340 |
return merchantOrder
|
|
|
341 |
|
|
|
342 |
def parseOrderRawHtml(self, orderId, subTagId, userId, rawHtml, orderSuccessUrl):
|
|
|
343 |
resp = {}
|
|
|
344 |
try:
|
| 15791 |
manish.sha |
345 |
rawHtmlSoup = BeautifulSoup(rawHtml)
|
|
|
346 |
emailId = None
|
|
|
347 |
orderObj = None
|
|
|
348 |
merchantOrderId = None
|
|
|
349 |
for script in rawHtmlSoup.find_all('script'):
|
|
|
350 |
if 'orderConfirmation' in script.text:
|
|
|
351 |
orderObj = json.loads(script.text.strip().split('\n')[0].split('orderConfirmation = ')[1].split(';')[0])
|
|
|
352 |
if merchantOrderId is None:
|
|
|
353 |
merchantOrderId = orderObj['0']['order_id']
|
|
|
354 |
emailId = orderObj['0']['email']
|
|
|
355 |
|
| 15509 |
manish.sha |
356 |
br = getBrowserObject()
|
| 15791 |
manish.sha |
357 |
url = ORDER_TRACK_URL +'&order_id=' +str(merchantOrderId)+'&email_id='+ emailId
|
| 15509 |
manish.sha |
358 |
page = br.open(url)
|
|
|
359 |
headers = str(page.info()).split('\n')
|
|
|
360 |
page = ungzipResponse(page)
|
|
|
361 |
jsonResponse = None
|
|
|
362 |
for header in headers:
|
|
|
363 |
header = header.split(':')
|
|
|
364 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
365 |
jsonResponse = json.loads(page)
|
|
|
366 |
if jsonResponse is not None:
|
|
|
367 |
page = jsonResponse['text']
|
|
|
368 |
|
| 15947 |
manish.sha |
369 |
merchantOrder = self._parseOrders(orderId, merchantOrderId, subTagId, userId, page, orderSuccessUrl, orderObj)
|
| 15509 |
manish.sha |
370 |
|
| 15948 |
manish.sha |
371 |
merchantOrder.orderTrackingUrl = ORDER_TRACK_URL_DB + 'order_id=' +str(merchantOrderId)+'&email_id='+ emailId
|
| 15509 |
manish.sha |
372 |
|
|
|
373 |
if self._saveToOrder(todict(merchantOrder)):
|
|
|
374 |
resp['result'] = 'ORDER_CREATED'
|
|
|
375 |
else:
|
|
|
376 |
resp['result'] = 'ORDER_ALREADY_CREATED_IGNORED'
|
|
|
377 |
|
|
|
378 |
return resp
|
|
|
379 |
except:
|
|
|
380 |
print "Error occurred"
|
|
|
381 |
traceback.print_exc()
|
|
|
382 |
resp['result'] = 'ORDER_NOT_CREATED'
|
| 16120 |
manish.sha |
383 |
return resp
|
| 15509 |
manish.sha |
384 |
|
| 15791 |
manish.sha |
385 |
def parseSingleSubOrder(self, soup, emailId, subOrderId):
|
|
|
386 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
|
|
387 |
subOrderStatus = orderStatusList[0].contents[0].strip()
|
| 15509 |
manish.sha |
388 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 15948 |
manish.sha |
389 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace("\r","").replace(" ","")
|
| 15509 |
manish.sha |
390 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 15791 |
manish.sha |
391 |
firstRow = orderTable.pop(0)
|
| 15949 |
manish.sha |
392 |
totalColumns = len(firstRow.find_all('th'))
|
| 15791 |
manish.sha |
393 |
subOrders =[]
|
|
|
394 |
count =1
|
| 15509 |
manish.sha |
395 |
for orderTr in orderTable:
|
|
|
396 |
cols = orderTr.find_all('td')
|
|
|
397 |
product_details = cols[0].find_all('a')
|
|
|
398 |
#print product_details
|
|
|
399 |
productUrl = product_details[0].get('href')
|
|
|
400 |
productName = product_details[0].contents[0].strip()
|
|
|
401 |
quantity = int(cols[1].text.strip())
|
| 15980 |
manish.sha |
402 |
sellingPrice = long(cols[2].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
403 |
discount = 0
|
|
|
404 |
subtotal = 0
|
|
|
405 |
if totalColumns == 5:
|
| 15949 |
manish.sha |
406 |
if cols[3].text.strip()!='-' and 'Rs.' in cols[3].text.strip():
|
| 15980 |
manish.sha |
407 |
discount = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
408 |
else:
|
|
|
409 |
discount = 0
|
| 15980 |
manish.sha |
410 |
subtotal = long(cols[4].text.strip().replace("Rs.","").replace(',',''))
|
| 15791 |
manish.sha |
411 |
else:
|
| 15980 |
manish.sha |
412 |
subtotal = long(cols[3].text.strip().replace("Rs.","").replace(',',''))
|
| 15509 |
manish.sha |
413 |
br = getBrowserObject()
|
|
|
414 |
productPage = br.open(BASE_MURL+productUrl)
|
|
|
415 |
productPageHeaders = str(productPage.info()).split('\n')
|
|
|
416 |
productPage = ungzipResponse(productPage)
|
|
|
417 |
jsonProductResponse = None
|
|
|
418 |
for header in productPageHeaders:
|
|
|
419 |
header = header.split(':')
|
|
|
420 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
421 |
jsonProductResponse = json.loads(productPage)
|
|
|
422 |
productPageSoup= None
|
|
|
423 |
if jsonProductResponse is not None:
|
|
|
424 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
|
|
425 |
else:
|
|
|
426 |
productPageSoup = BeautifulSoup(productPage)
|
| 15791 |
manish.sha |
427 |
productCode = productPageSoup.find('input', {'type':'hidden'})['value']
|
| 15509 |
manish.sha |
428 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
|
|
429 |
productImgUrl = ''
|
|
|
430 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
|
|
431 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
|
|
432 |
|
|
|
433 |
subOrder = SubOrder(productName, productUrl, placedOn, subtotal)
|
| 15791 |
manish.sha |
434 |
subOrder.merchantSubOrderId = str(subOrderId)+'-'+str(count)
|
| 15509 |
manish.sha |
435 |
subOrder.detailedStatus = subOrderStatus
|
|
|
436 |
subOrder.imgUrl = productImgUrl
|
|
|
437 |
subOrder.offerDiscount = discount*quantity
|
|
|
438 |
subOrder.unitPrice = sellingPrice
|
|
|
439 |
subOrder.productCode = productCode
|
|
|
440 |
subOrder.amountPaid = subtotal
|
|
|
441 |
subOrder.quantity = quantity
|
| 15791 |
manish.sha |
442 |
subOrder.tracingkUrl = ORDER_TRACK_URL_DB + 'order_id=' +subOrderId+'&email_id='+ emailId
|
| 15509 |
manish.sha |
443 |
subOrders.append(subOrder)
|
| 15791 |
manish.sha |
444 |
count = count +1
|
| 15509 |
manish.sha |
445 |
|
|
|
446 |
subOrders = self.updateCashbackInSubOrders(subOrders)
|
| 15791 |
manish.sha |
447 |
return subOrders
|
| 15509 |
manish.sha |
448 |
|
| 15791 |
manish.sha |
449 |
def parseMultiSubOrders(self, soup, emailId):
|
| 15509 |
manish.sha |
450 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
| 16145 |
manish.sha |
451 |
firstRow = orderTable.pop(0)
|
| 15791 |
manish.sha |
452 |
'''
|
|
|
453 |
totalColumns = len(firstRow.find_all('td'))
|
|
|
454 |
|
| 15509 |
manish.sha |
455 |
orderDateList = soup.findAll(attrs={'class':'price ord_date'})
|
| 15791 |
manish.sha |
456 |
placedOn= orderDateList[0].text.strip().replace("\t","").replace("\n","").replace(" ","")
|
|
|
457 |
'''
|
| 15509 |
manish.sha |
458 |
subOrders = []
|
| 15791 |
manish.sha |
459 |
existingOrders = []
|
| 15509 |
manish.sha |
460 |
for orderTr in orderTable:
|
|
|
461 |
cols = orderTr.find_all('td')
|
|
|
462 |
product_details = cols[0].find_all('a')
|
|
|
463 |
#print product_details
|
|
|
464 |
subOrderId= product_details[1].contents[0].strip()
|
| 15791 |
manish.sha |
465 |
if subOrderId in existingOrders:
|
|
|
466 |
continue
|
|
|
467 |
else:
|
|
|
468 |
existingOrders.append(subOrderId)
|
|
|
469 |
'''
|
| 15509 |
manish.sha |
470 |
productUrl = product_details[0].get('href')
|
|
|
471 |
productName = product_details[0].contents[0].strip()
|
| 15791 |
manish.sha |
472 |
'''
|
|
|
473 |
subOrderTrackingParsingUrl = product_details[1].get('href')
|
|
|
474 |
#subOrderTrackingUrl = subOrderTrackingParsingUrl.split('order_lookup.details&')[1]
|
|
|
475 |
'''
|
| 15509 |
manish.sha |
476 |
quantity = int(cols[1].text.strip())
|
|
|
477 |
sellingPrice = long(cols[2].text.strip().replace("Rs.",""))
|
| 15791 |
manish.sha |
478 |
discount = 0
|
|
|
479 |
subtotal = 0
|
|
|
480 |
if totalColumns == 5:
|
|
|
481 |
if cols[3].text.strip()!='-' or 'Rs.' in cols[3].text.strip():
|
|
|
482 |
discount = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
483 |
else:
|
|
|
484 |
discount = 0
|
|
|
485 |
subtotal = long(cols[4].text.strip().replace("Rs.",""))
|
|
|
486 |
else:
|
|
|
487 |
subtotal = long(cols[3].text.strip().replace("Rs.",""))
|
|
|
488 |
|
| 15509 |
manish.sha |
489 |
br = getBrowserObject()
|
|
|
490 |
productPage = br.open(BASE_MURL+productUrl)
|
|
|
491 |
productPageHeaders = str(productPage.info()).split('\n')
|
|
|
492 |
productPage = ungzipResponse(productPage)
|
|
|
493 |
jsonProductResponse = None
|
|
|
494 |
for header in productPageHeaders:
|
|
|
495 |
header = header.split(':')
|
|
|
496 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
497 |
jsonProductResponse = json.loads(productPage)
|
|
|
498 |
productPageSoup= None
|
|
|
499 |
if jsonProductResponse is not None:
|
|
|
500 |
productPageSoup = BeautifulSoup(jsonProductResponse['text'])
|
|
|
501 |
else:
|
|
|
502 |
productPageSoup = BeautifulSoup(productPage)
|
| 15791 |
manish.sha |
503 |
productCode = productPageSoup.find('input', {'type':'hidden'})['value']
|
| 15509 |
manish.sha |
504 |
allproductImageTags = productPageSoup.findAll(attrs={'class' : 'pd-image'})
|
|
|
505 |
productImgUrl = ''
|
|
|
506 |
if allproductImageTags is not None and len(allproductImageTags)>0:
|
|
|
507 |
productImgUrl= allproductImageTags[0].get('style').split("background:url('")[1].split("')no-repeat center")[0].strip()
|
|
|
508 |
productDetailsSubMap['productCode']=productCode
|
|
|
509 |
productDetailsSubMap['imgUrl']=productImgUrl
|
| 15791 |
manish.sha |
510 |
'''
|
| 15509 |
manish.sha |
511 |
br1 = getBrowserObject()
|
| 15791 |
manish.sha |
512 |
orderTrackingPage = br1.open(BASE_URL+'&'+subOrderTrackingParsingUrl)
|
| 15509 |
manish.sha |
513 |
headers = str(orderTrackingPage.info()).split('\n')
|
|
|
514 |
orderTrackingPage= ungzipResponse(orderTrackingPage)
|
|
|
515 |
jsonResponse = None
|
|
|
516 |
for header in headers:
|
|
|
517 |
header = header.split(':')
|
|
|
518 |
if header[0] == 'Content-Type' and 'json' in header[1]:
|
|
|
519 |
jsonResponse = json.loads(orderTrackingPage)
|
|
|
520 |
|
|
|
521 |
orderTrackingPageSoup = None
|
|
|
522 |
if jsonResponse is not None:
|
|
|
523 |
orderTrackingPageSoup = BeautifulSoup(str(jsonResponse['text']))
|
|
|
524 |
else:
|
|
|
525 |
orderTrackingPageSoup = BeautifulSoup(orderTrackingPage)
|
| 15791 |
manish.sha |
526 |
subOrdersDetails = self.parseSingleSubOrder(orderTrackingPageSoup, emailId, subOrderId)
|
|
|
527 |
subOrders = list(set(subOrders + subOrdersDetails))
|
| 15509 |
manish.sha |
528 |
|
| 15791 |
manish.sha |
529 |
return subOrders
|
| 15509 |
manish.sha |
530 |
|
|
|
531 |
def scrapeStoreOrders(self,):
|
|
|
532 |
#collectionMap = {'palcedOn':1}
|
|
|
533 |
searchMap = {}
|
|
|
534 |
collectionMap = {"orderTrackingUrl":1}
|
|
|
535 |
orders = self._getActiveOrders(searchMap,collectionMap)
|
|
|
536 |
for order in orders:
|
|
|
537 |
print "Order", self.store_name, order['orderId'], order['orderTrackingUrl']
|
| 16138 |
manish.sha |
538 |
url = ORDER_TRACK_URL +'&'+ order['orderTrackingUrl'].split('trackOrder?')[1]
|
| 16141 |
manish.sha |
539 |
print url
|
| 15509 |
manish.sha |
540 |
page = fetchResponseUsingProxy(url)
|
|
|
541 |
soup = BeautifulSoup(page)
|
|
|
542 |
bulk = self.db.merchantOrder.initialize_ordered_bulk_op()
|
|
|
543 |
closed = True
|
| 16144 |
manish.sha |
544 |
orderIdSpan = soup.body.find("span", {'class':'price ord_no'})
|
|
|
545 |
if orderIdSpan is not None:
|
| 16143 |
manish.sha |
546 |
orderStatusList = soup.findAll(attrs={'class' : 'price ord_status'})
|
|
|
547 |
print orderStatusList
|
|
|
548 |
print 'Length Of Order Status List ',len(orderStatusList)
|
|
|
549 |
if orderStatusList is not None and len(orderStatusList)>0:
|
|
|
550 |
subOrderId = soup.findAll(attrs={'class':'price ord_no'})[0].text.strip()
|
|
|
551 |
orderStatus = orderStatusList[0].contents[0].strip()
|
|
|
552 |
orderTable = soup.body.find("table", {'class':'table product-list'}).findAll('tr', recursive=False)
|
|
|
553 |
orderTable.pop(0)
|
|
|
554 |
count = 1
|
|
|
555 |
while count <= len(orderTable):
|
|
|
556 |
subOrder = self._isSubOrderActive(order, str(subOrderId)+'-'+str(count))
|
|
|
557 |
count = count +1
|
|
|
558 |
if subOrder is None:
|
|
|
559 |
try:
|
|
|
560 |
subOrders = self.parseSingleSubOrder(soup, order['orderTrackingUrl'].split('email_id=')[1], subOrderId)
|
|
|
561 |
for subOrder in subOrders:
|
|
|
562 |
if subOrder is None:
|
|
|
563 |
continue
|
|
|
564 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrder])}}})
|
|
|
565 |
print "Added new suborders to Order id - ", order['orderId']
|
|
|
566 |
closed = False
|
|
|
567 |
except:
|
|
|
568 |
pass
|
|
|
569 |
continue
|
|
|
570 |
elif subOrder['closed']:
|
|
|
571 |
continue
|
|
|
572 |
else:
|
|
|
573 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": subOrderId}
|
|
|
574 |
updateMap = {}
|
|
|
575 |
updateMap["subOrders.$.detailedStatus"] = orderStatus
|
|
|
576 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
|
|
577 |
closedStatus = status in [Store.ORDER_DELIVERED, Store.ORDER_CANCELLED]
|
|
|
578 |
if status is not None:
|
|
|
579 |
updateMap["subOrders.$.status"] = status
|
|
|
580 |
if closedStatus:
|
|
|
581 |
#if status is closed then change the paybackStatus accordingly
|
|
|
582 |
updateMap["subOrders.$.closed"] = True
|
|
|
583 |
if status == Store.ORDER_DELIVERED:
|
|
|
584 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
585 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_APPROVED
|
|
|
586 |
elif status == Store.ORDER_CANCELLED:
|
|
|
587 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
588 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_CANCELLED
|
|
|
589 |
else:
|
| 15791 |
manish.sha |
590 |
closed = False
|
| 16143 |
manish.sha |
591 |
bulk.find(findMap).update({'$set' : updateMap})
|
|
|
592 |
|
|
|
593 |
else:
|
|
|
594 |
subOrdersList = self.parseMultiSubOrders(soup, order['orderTrackingUrl'].split('email_id=')[1])
|
|
|
595 |
for subOrderObj in subOrdersList:
|
|
|
596 |
subOrder = self._isSubOrderActive(order, subOrderObj.merchantSubOrderId)
|
|
|
597 |
if subOrder is None:
|
|
|
598 |
self.db.merchantOrder.update({"orderId":order['orderId']},{'$push':{"subOrders":{"$each":todict([subOrderObj])}}})
|
|
|
599 |
print "Added new suborders to Order id - ", order['orderId']
|
|
|
600 |
closed = False
|
|
|
601 |
continue
|
|
|
602 |
elif subOrder['closed']:
|
|
|
603 |
continue
|
| 15791 |
manish.sha |
604 |
else:
|
| 16143 |
manish.sha |
605 |
findMap = {"orderId": order['orderId'], "subOrders.merchantSubOrderId": subOrderId}
|
|
|
606 |
updateMap = {}
|
|
|
607 |
updateMap["subOrders.$.detailedStatus"] = subOrderObj.detailedStatus
|
|
|
608 |
status = self._getStatusFromDetailedStatus(orderStatus)
|
|
|
609 |
closedStatus = status in [Store.ORDER_DELIVERED, Store.ORDER_CANCELLED]
|
|
|
610 |
if status is not None:
|
|
|
611 |
updateMap["subOrders.$.status"] = status
|
|
|
612 |
if closedStatus:
|
|
|
613 |
#if status is closed then change the paybackStatus accordingly
|
|
|
614 |
updateMap["subOrders.$.closed"] = True
|
|
|
615 |
if status == Store.ORDER_DELIVERED:
|
|
|
616 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
617 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_APPROVED
|
|
|
618 |
elif status == Store.ORDER_CANCELLED:
|
|
|
619 |
if subOrder.get("cashBackStatus") == Store.CB_PENDING:
|
|
|
620 |
updateMap["subOrders.$.cashBackStatus"] = Store.CB_CANCELLED
|
|
|
621 |
else:
|
|
|
622 |
closed = False
|
|
|
623 |
bulk.find(findMap).update({'$set' : updateMap})
|
|
|
624 |
bulk.find({'orderId': order['orderId']}).update({'$set':{'closed': closed,"parseError":False}})
|
|
|
625 |
result = bulk.execute()
|
|
|
626 |
tprint(result)
|
| 15509 |
manish.sha |
627 |
else:
|
| 16143 |
manish.sha |
628 |
print 'Soup Object not found for this Order', order['orderId'], order['orderTrackingUrl']
|
|
|
629 |
continue
|
| 15791 |
manish.sha |
630 |
|
|
|
631 |
'''
|
|
|
632 |
def getTrackingUrls(self, userId):
|
|
|
633 |
missingOrderUrls = ['https://sm.shopclues.com/myaccount','https://sm.shopclues.com/myorders']
|
|
|
634 |
return missingOrderUrls
|
| 15509 |
manish.sha |
635 |
|
| 15791 |
manish.sha |
636 |
def parseMyProfileForEmailId(self, userId, url, rawhtml):
|
|
|
637 |
profileSoup = BeautifulSoup(rawhtml)
|
|
|
638 |
if profileSoup.find('input', {'name':'user_email'}) is not None:
|
|
|
639 |
emailId = profileSoup.find('input', {'name':'user_email'})['value']
|
|
|
640 |
if emailId is not None and emailId.strip() !='':
|
|
|
641 |
mc = MemCache()
|
|
|
642 |
mc.set(str(userId), emailId, 600)
|
|
|
643 |
return 'EMAIL_SET_SUCCESS'
|
|
|
644 |
else:
|
|
|
645 |
return 'EMAIL_NOT_FOUND'
|
|
|
646 |
else:
|
|
|
647 |
return 'EMAIL_NOT_FOUND'
|
| 15509 |
manish.sha |
648 |
|
| 15791 |
manish.sha |
649 |
def parseMyOrdersForEmailId(self, userId, url, rawhtml):
|
|
|
650 |
myOrdersPageSoup = BeautifulSoup(rawhtml)
|
|
|
651 |
if myOrdersPageSoup.find('a', {'class':'detail'}) is not None:
|
|
|
652 |
emailId = myOrdersPageSoup.find('a', {'class':'detail'})['href'].split('&')[1].split('=')[1]
|
|
|
653 |
mc = MemCache()
|
|
|
654 |
mc.set(str(userId), emailId, 600)
|
|
|
655 |
return 'EMAIL_SET_SUCCESS'
|
|
|
656 |
else:
|
|
|
657 |
return 'EMAIL_NOT_FOUND'
|
|
|
658 |
'''
|
|
|
659 |
|
|
|
660 |
|
| 15509 |
manish.sha |
661 |
def todict(obj, classkey=None):
|
|
|
662 |
if isinstance(obj, dict):
|
|
|
663 |
data = {}
|
|
|
664 |
for (k, v) in obj.items():
|
|
|
665 |
data[k] = todict(v, classkey)
|
|
|
666 |
return data
|
|
|
667 |
elif hasattr(obj, "_ast"):
|
|
|
668 |
return todict(obj._ast())
|
|
|
669 |
elif hasattr(obj, "__iter__"):
|
|
|
670 |
return [todict(v, classkey) for v in obj]
|
|
|
671 |
elif hasattr(obj, "__dict__"):
|
|
|
672 |
data = dict([(key, todict(value, classkey))
|
|
|
673 |
for key, value in obj.__dict__.iteritems()
|
|
|
674 |
if not callable(value) and not key.startswith('_')])
|
|
|
675 |
if classkey is not None and hasattr(obj, "__class__"):
|
|
|
676 |
data[classkey] = obj.__class__.__name__
|
|
|
677 |
return data
|
|
|
678 |
else:
|
| 15791 |
manish.sha |
679 |
return obj
|
|
|
680 |
|
| 15509 |
manish.sha |
681 |
|