-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshopifyService.py
311 lines (246 loc) · 9.45 KB
/
shopifyService.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
import requests
from model import Product
import re
import time
import json
import datetime
keys = {}
with open("keys.json") as f:
keys = json.load(f)
# shopify api credentials
api_key = keys['api_key']
password = keys['api_secret']
store = keys['store']
url = "https://"+api_key+":"+password + \
"@"+store+".myshopify.com/admin/api/2021-04/products.json"
url_delete_all = url + "?fields=id&limit=250&since_id=6952463138999"
product_list_url = url+"?fields=id,variants&limit=200"
inventory_url = "https://"+api_key+":"+password + \
"@"+store+".myshopify.com/admin/api/2021-04/inventory_items/"
product_list = [] # shopifyProducts to be filed from shopify getAllProducts
def getAllProducts(): # get all shopify products and save them into a json file
print("Getting all shopify products ....")
getProducts(product_list_url)
with open('data.json', 'w') as f:
json.dump(product_list, f)
print("Shopify products List size : "+str(len(product_list)))
def getProducts(url): # get shopify products
global index
index = index+1
print("page : "+str(index))
time.sleep(501/1000)
headers = {"Accept": "application/json",
"Content-Type": "application/json",
"X-Shopify-Access-Token": password}
try:
r = requests.get(url, headers=headers, timeout=10)
data = r.json()
products = data['products']
for p in products:
product_list.append(p)
if "rel=\"next\"" in r.headers['Link']:
next = ''
urls = findUrlInString(r.headers['Link'])
if len(urls) == 1:
next = urls[0]
else:
next = urls[1]
getProducts(next)
except requests.exceptions.Timeout as e:
print(e)
time.sleep(2)
getProducts(url)
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
raise SystemExit(e)
def createProduct(product: Product):
url = "https://"+api_key+":"+password + \
"@"+store+".myshopify.com/admin/api/2021-04/products.json"
pushProduct("create", url, product)
def updateProduct(product: Product, product_id):
url = "https://"+api_key+":"+password + \
"@"+store+".myshopify.com/admin/api/2021-04/products/" + \
str(product_id)+".json"
pushProduct("update", url, product)
def pushProduct(call, api_product, product: Product):
time.sleep(520/1000)
images = []
if len(product.pictures) > 0:
for img in product.pictures:
images.append({'src': img})
status = "active"
payload = {
"product": {
"title": product.title,
"body_html": product.description,
"images": images,
"product_type": product.category,
"vendor": product.brandName,
# "metafields_global_description_tag": product.description,
"status": status,
"variants": [
{
"barcode": product.barcode,
"price": product.price,
"compare_at_price": product.compare_at_price,
"tracked": True,
# "inventory_item_id": 1, # to be gotten by get inventory endpoint
"inventory_quantity": product.quantity,
"sku": product.sku,
"weight": product.weight,
"weight_unit": "lb"
}
]
}
}
headers = {"Accept": "application/json",
"Content-Type": "application/json",
"X-Shopify-Access-Token": password}
try:
r = ""
if call == "create":
r = requests.post(api_product, json=payload,
headers=headers, timeout=10)
else:
r = requests.put(api_product, json=payload,
headers=headers, timeout=10)
data = r.json()
if "errors" in data.keys():
print(data, flush=True)
if r.status_code == 201 or (call == "update" and r.status_code == 200):
product_id = data['product']['id']
inventory_id = data['product']['variants'][0]['inventory_item_id']
created_string = " product with id : " + \
str(product_id) + " : "+call+"d , SKU : "+product.sku
print(created_string, flush=True)
inventory_data = {
"id": inventory_id,
"cost": product.netPrice
}
if call == "update":
inventory_data = getInventoryItem(inventory_id)
if inventory_data is None:
inventory_data = {
"id": inventory_id,
"cost": product.netPrice
}
inventory_data['id'] = inventory_id
inventory_data['cost'] = product.netPrice
updateInventoryItem(inventory_data)
return r.status_code
except requests.exceptions.Timeout as e:
print(e, flush=True)
return None
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
raise SystemExit(e)
# assing product with matched collection
def pushProductToCollection(product_id, collection_id):
time.sleep(520/1000)
url = "https://"+api_key+":"+password + \
"@"+store+".myshopify.com/admin/api/2021-04/collects.json"
payload = {
"collect": {
"product_id": product_id,
"collection_id": collection_id
}
}
headers = {"Accept": "application/json",
"Content-Type": "application/json",
"X-Shopify-Access-Token": password}
try:
r = requests.post(url, json=payload, headers=headers, timeout=10)
print(" pushed product to collect ")
print(r.data())
return r.status_code
except requests.exceptions.Timeout as e:
print(e, flush=True)
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
raise SystemExit(e)
def createCustomCollection(title):
time.sleep(520/1000)
url = url = "https://"+api_key+":"+password + \
"@"+store+".myshopify.com/admin/api/2021-04/custom_collections.json"
payload = {
"custom_collection": {
"title": title
}
}
headers = {"Accept": "application/json",
"Content-Type": "application/json",
"X-Shopify-Access-Token": password}
try:
r = requests.post(url, json=payload, headers=headers, timeout=10)
data = r.json()
if r.status_code == 201:
return data['custom_collection']['id']
else:
return None
except requests.exceptions.Timeout as e:
print(e, flush=True)
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
raise SystemExit(e)
# shopify products list , that contains all shopify products
# url
# product_list : an empty list of ShopifyProductDTO , that is passed as reference
index = 0
# get http url from text
def findUrlInString(string):
# findall() has been used
# with valid conditions for urls in string
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
url = re.findall(regex, string)
return [x[0] for x in url]
def getInventoryItem(inventory_id):
time.sleep(520/1000)
url = inventory_url+str(inventory_id)+".json"
headers = {"Accept": "application/json",
"Content-Type": "application/json",
"X-Shopify-Access-Token": password}
try:
r = requests.get(url, headers=headers, timeout=10)
data = r.json()
if r.status_code == 200:
return data['inventory_item']
else:
return None
except requests.exceptions.Timeout as e:
print(e, flush=True)
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
raise SystemExit(e)
def updateInventoryItem(inventory_data):
time.sleep(520/1000)
url = inventory_url+str(inventory_data['id'])+".json"
payload = {
"inventory_item": inventory_data
}
headers = {"Accept": "application/json",
"Content-Type": "application/json",
"X-Shopify-Access-Token": password}
try:
r = requests.put(url, json=payload, headers=headers, timeout=10)
data = r.json()
if r.status_code == 200:
return data['inventory_item']['id']
else:
inventory_string = "Inventory not updated, inventory_id : " + \
str(inventory_data['id'])
print(inventory_string, flush=True)
return None
except requests.exceptions.Timeout as e:
print(e, flush=True)
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
raise SystemExit(e)
def getCurrentTime():
date = datetime.datetime.now(datetime.timezone.utc)
return date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")