-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestPythonApi.py
387 lines (346 loc) · 15 KB
/
testPythonApi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import api2
import csv
<<<<<<< HEAD
import datetime
import time
from email.utils import formatdate
=======
>>>>>>> bbf7922041d024f151165b596556cd81b3ae1254
#API_HOST = 'https://store-1eaef.mybigcommerce.com'
API_HOST = 'https://store-cbfd8.mybigcommerce.com'
API_PATH = '/api/v2'
API_USER = 'admin'
#API_KEY = '0270f4680ac3eb5796ab3f9fe5a0e46299fe14cd'
API_KEY = 'e3a4804855753b8981e4787115c65edbccd339df'
conn = api2.Connection(API_HOST,API_PATH,API_USER,API_KEY)
store_categories = api2.Categories(client=conn)
store_products = api2.Products(client=conn)
store_orders = api2.Orders(client=conn)
store_images = api2.Image(client=conn)
<<<<<<< HEAD
store_shipments = api2.Shipments(client=conn)
store_orderProducts = api2.OrderProduct(client=conn)
=======
>>>>>>> bbf7922041d024f151165b596556cd81b3ae1254
def allCategories(): #checks categories listed
categories = store_categories.get()
allCategories = []
for category in categories:
allCategories.append(category.name)
return allCategories
<<<<<<< HEAD
def allCategoriesClass():
categories = store_categories.get()
allCategories = []
for category in categories:
allCategories.append(category)
return allCategories
=======
>>>>>>> bbf7922041d024f151165b596556cd81b3ae1254
def allProducts(): #returns all products in a list with names
products = store_products.get()
allProducts = []
for product in products:
allProducts.append(product.name)
return allProducts
def allProductsClass(): #returns all products in a list as a class
products = store_products.get()
allProducts = []
for product in products:
allProducts.append(product)
return allProducts
def checkCategories(): #checks categories listed
categories = store_categories.get()
allcategories = []
for category in categories:
<<<<<<< HEAD
print category.name,category.id
=======
print category.name
>>>>>>> bbf7922041d024f151165b596556cd81b3ae1254
def checkProducts(): #checks all products listed
products = store_products.get()
for product in products:
print "Name:", product.name
print "ID:",product.id
#print "SKU:", product.sku
#print "Price:", product.price
def checkOrders(): #checks orders
orders = store_orders.get()
for order in orders:
<<<<<<< HEAD
print "order", store_orders.get_by_id(order.id)
print "created:", store_orders.getOrderProductName(order.id)
#print "modified:", order.date_modified
#order.status = 'Refunded'
def storeOrdersWithID():
orders = store_orders.get()
ordersWithID = dict()
for order in orders:
ordersWithID[order.products['url']] = order.id
return ordersWithID
def storeProductsWithID():
products = store_products.get()
productsWithID = dict()
for product in products:
productsWithID[product.name] = product.id
return productsWithID
def storeCategoriesWithID():
categories = store_categories.get()
categoriesWithID = dict()
for category in categories:
categoriesWithID[category.name] = category.id
return categoriesWithID
def convertDateToRfc(lastUpdated):
#'25-May-2012'
monthToNumber = {"January":1,"Jan":1,"February":2,"Feb":2,"March":3,"Mar":3,
"April":4,"Apr":4,"May":5,"Jun":6,"Jul":7,"August":8,
"Aug":8,"Sep":9,"Oct":10,"Nov":11,"Dec":12}
timeSplit = lastUpdated.split("-") #[Day,Month,Year]
(day,month,year) = int(timeSplit[0]),timeSplit[1],int(timeSplit[2])
monthNumber = monthToNumber[month]
if (year < 13): #current year
year = 2000 + year
else:
year = 1900 + year
time_tuple = (year,monthNumber,day,0,0,0,0,0,0)
timeStamp = time.mktime(time_tuple)
return formatdate(timeStamp)
def createShipments(ID,orderAddressID,trackingNumber,
comments,orderProductID,quantity):
#order = store_orders.get_by_id(ID)
#productsWithID = storeProductsWithID()
#productName = store_orders.getOrderProductName(ID)
#orderProduct = store_orderProducts.orderProductget_by_id(ID)
print orderProductID
shipment = store_shipments.create(ID,{"order_address_id":orderAddressID,
"tracking_number":trackingNumber,
"comments":comments,
"items":[{u'order_product_id': orderProductID,
u'quantity': quantity}]})
def addProduct(name,category,price,weight,description,visible,
lastUpdated,typ='physical',availability='available'):
rfcLastUpdated = convertDateToRfc(lastUpdated)
newProduct = store_products.add({"name":name,'categories':category,
"price":price,"is_visible":visible,
"date_modified":rfcLastUpdated,
"description":description,
=======
print "created:", order.date_created
#print "modified:", order.date_modified
#order.status = 'Refunded'
def createProduct(name,category,price,weight,typ='physical',availability='available'):
newProduct = store_products.add({"name":name,'categories':category,
"price":price,"is_visible":True,
>>>>>>> bbf7922041d024f151165b596556cd81b3ae1254
"type":typ,'weight':weight,
'availability':availability})
def deleteProductID(ID):
product = store_products.get_by_id(ID)
product.delete()
<<<<<<< HEAD
def updateOrderWithID(ID,billingAddress,shippingAddress):
order = store_orders.get_by_id(ID)
order.update_field("status",u'Shipped')
#order = store_or
#order.update_field("billing_address",billingAddress)
#order.update_field("shippingAddress",shippingAddress)
def updateProductWithID(ID,name,category,price,weight,
description,visible,lastUpdated,typ='physical',
availability='available'): #updates product
product = store_products.get_by_id(ID)
product.update_field("name",name)
product.update_field("categories",category)
product.update_field("price",price)
product.update_field("weight",weight)
product.update_field("description",description)
product.update_field("is_visible",visible)
#print "dateMOD:", lastUpdated
product.update_field("date_modified",convertDateToRfc(lastUpdated))
def addCategory(newCategories):
count = 0
for newCategory in newCategories:
if count == 0: #adds Parent (first) category
print newCategory
newCategory = store_categories.add({"name":newCategory})
print "newCategory:",newCategory
newCategoryID = newCategory.get("id")
else: #for Sub-Categories
newCategory = store_categories.add({"name":newCategory,
"parent_id": newCategoryID})
subCategoryID = newCategory.get("id")
count += 1
return subCategoryID
def addSubCategory(newCategories,categoryID): #if category exists, but not subcategory
count = 0
for newCategory in newCategories:
count += 1
if count == 1: #skips Parent (first) category
newCategory = store_categories.get_by_id(categoryID)
#print "newCat:", newCategory
newCategoryID = newCategory.id
else:
newCategory = store_categories.add({"name":newCategory,
"parent_id":newCategoryID})
subCategoryID = newCategory.get("id")
return subCategoryID
def findSubCategory(newCategories): #from most specific sub category
#print "newCat:", newCategories
categoriesWithID = storeCategoriesWithID()
subCategoryID = categoriesWithID[newCategories[-1]]
return subCategoryID
=======
def updateProductID(ID,image):
product = store_products.get_by_id(ID)
product.images = image
product.update()
>>>>>>> bbf7922041d024f151165b596556cd81b3ae1254
def checkIfCommon(c1,categories):#compares categories listed with all categories
for category in categories:
for categoryListed in c1:
<<<<<<< HEAD
#print "categoryListed:", categoryListed
#print "category.name:", category.name
if categoryListed == category.name:
return (True,category.name,category.id)
return (False,None,0)
def currentDay():
now = datetime.datetime.now()
time = str(now.day)+"-"+now.strftime("%B")+"-"+str(now.year)[-2:]
return time
def addFromCsv(): #adds from CSV file (currently only adds one product)
with open('DealExtreme_Small_DateUpdatedColumn.csv','rb') as f:
reader = csv.reader(f)
count = 0
productsWithID = storeProductsWithID()#dictionary with product name and id
categoriesWithID = storeCategoriesWithID()
for product in reader: #each product is stored as a list with details
try:
count += 1
if count == 1: #first row with name of details (title,weight,etc)
continue
name = product[13] #index 13 is title
print "name:", name
price = product[5][1:] #gets rid of dollar sign
specifications = product[3]
index = specifications.index("Weight")
weight = specifications[index+8:]
description = product[4]
visible = product[19]
if visible == "yes":
visible = True
else:
visible = False
lastUpdated = product[20]
image = "http://" + product[8].split(",")[0] #gets rid of space
if (name in allProducts()) and (lastUpdated != currentDay()):
#product exists and updated
continue
categoriesListed = product[10].split(",")
categories = allCategoriesClass()
if checkIfCommon(categoriesListed,categories)[0]: #category exists
categoryID = checkIfCommon(categoriesListed,categories)[2]
if len(categories) == 1:
categoryIndex = findSubCategory(categoriesListed)
if checkIfCommon(categoriesListed[1:],categories)[0]:
#subCategory exists
category = checkIfCommon(categoriesListed,categories)[1]
#print name,category
categories = allCategoriesClass() #updated categories
#categoryIndex = checkIfCommon(categoriesListed,
# categories)[2]
categoryIndex = findSubCategory(categoriesListed)
else:
#adding subCategory
categoryIndex = addSubCategory(categoriesListed,categoryID)
categories = allCategoriesClass()
#Category identity
else: #if categoryListed doesn't match those of site category
categoryIndex = addCategory(categoriesListed)
category = checkIfCommon(categoriesListed,categories)[1]
categories = allCategoriesClass() #updated categories after adding
assert (checkIfCommon(categoriesListed,categories)[0] == True)
#print "new"
#print name,category
#Category identity
#print categoryIndex
#print price
#print weight
#print image
if (name in allProducts()) and (lastUpdated == currentDay()):
#product exists and not updated
updateProductWithID(productsWithID[name],name,[categoryIndex],
price,weight,description,visible,lastUpdated)
continue
addProduct(name,[categoryIndex],price,weight,description,visible,
lastUpdated)
lastProductID = allProductsClass()[-1].id
images = store_images.create(lastProductID,{"image_file":image})
#print lastProductID
if count == 1000: #TEMPORARY (stops after one product)
break
except:
print "skipped:"
def readCsv(): #reads from csv file
with open('DealExtreme_Small_DateUpdatedColumn.csv','rb') as f:
=======
if categoryListed in category:
return (True,category)
elif category in categoryListed:
return (True,category)
return (False,None)
def addFromCsv(): #adds from CSV file (currently only adds one product)
with open('dealextreme.csv','rb') as f:
reader = csv.reader(f)
count = 0
for product in reader: #each product is stored as a list with details
name = product[13] #index 13 is title
categoriesListed = product[10].split(",")
categories = allCategories()
if checkIfCommon(categoriesListed,allCategories())[0]:
category = checkIfCommon(categoriesListed,allCategories())[1]
categoryIndex = categories.index(category)
price = product[5][1:] #gets rid of dollar sign
specifications = product[3]
count += 1
if count == 1:
continue
index = specifications.index("Weight")
weight = specifications[index+8:]
image = "http://" + product[8].split(",")[0] #gets rid of space
#print name
#print categoryIndex
#print price
#print weight
#print image
lastProductID = allProductsClass()[-1].id
if count == 3: #TEMPORARY (stops after one product)
break
if name in allProducts():
continue
createProduct(name,[categoryIndex],price,weight)
lastProductID = allProductsClass()[-1].id
images = store_images.create(lastProductID,{"image_file":image})
#print lastProductID
if count == 3: #TEMPORARY (stops after one product)
break
def readCsv(): #reads from csv file
with open('dealextreme.csv','rb') as f:
>>>>>>> bbf7922041d024f151165b596556cd81b3ae1254
reader = csv.reader(f)
count = 0
for row in reader:
print row
count +=1
if count == 4:
break
def writecsv(): #writes a file as a csv file
with open('some.csv', 'wb') as f:
try:
writer = csv.writer(f)
writer.writerow(('Height','Width','Length'))
for i in xrange(5):
writer.writerow((i,i*2,i/3))
finally:
f.close
print open('some.csv','rt').read()