-
Notifications
You must be signed in to change notification settings - Fork 89
/
seller.py
185 lines (157 loc) · 6.07 KB
/
seller.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
import io
import logging.config
import os
import re
import zipfile
from environs import Env
import pandas as pd
import requests
logger = logging.getLogger(__file__)
def get_product_list(last_id, client_id, seller_token):
"""Получить список товаров магазина озон"""
url = "https://api-seller.ozon.ru/v2/product/list"
headers = {
"Client-Id": client_id,
"Api-Key": seller_token,
}
payload = {
"filter": {
"visibility": "ALL",
},
"last_id": last_id,
"limit": 1000,
}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
response_object = response.json()
return response_object.get("result")
def get_offer_ids(client_id, seller_token):
"""Получить артикулы товаров магазина озон"""
last_id = ""
product_list = []
while True:
some_prod = get_product_list(last_id, client_id, seller_token)
product_list.extend(some_prod.get("items"))
total = some_prod.get("total")
last_id = some_prod.get("last_id")
if total == len(product_list):
break
offer_ids = []
for product in product_list:
offer_ids.append(product.get("offer_id"))
return offer_ids
def update_price(prices: list, client_id, seller_token):
"""Обновить цены товаров"""
url = "https://api-seller.ozon.ru/v1/product/import/prices"
headers = {
"Client-Id": client_id,
"Api-Key": seller_token,
}
payload = {"prices": prices}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.json()
def update_stocks(stocks: list, client_id, seller_token):
"""Обновить остатки"""
url = "https://api-seller.ozon.ru/v1/product/import/stocks"
headers = {
"Client-Id": client_id,
"Api-Key": seller_token,
}
payload = {"stocks": stocks}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.json()
def download_stock():
"""Скачать файл ostatki с сайта casio"""
# Скачать остатки с сайта
casio_url = "https://timeworld.ru/upload/files/ostatki.zip"
session = requests.Session()
response = session.get(casio_url)
response.raise_for_status()
with response, zipfile.ZipFile(io.BytesIO(response.content)) as archive:
archive.extractall(".")
# Создаем список остатков часов:
excel_file = "ostatki.xls"
watch_remnants = pd.read_excel(
io=excel_file,
na_values=None,
keep_default_na=False,
header=17,
).to_dict(orient="records")
os.remove("./ostatki.xls") # Удалить файл
return watch_remnants
def create_stocks(watch_remnants, offer_ids):
# Уберем то, что не загружено в seller
stocks = []
for watch in watch_remnants:
if str(watch.get("Код")) in offer_ids:
count = str(watch.get("Количество"))
if count == ">10":
stock = 100
elif count == "1":
stock = 0
else:
stock = int(watch.get("Количество"))
stocks.append({"offer_id": str(watch.get("Код")), "stock": stock})
offer_ids.remove(str(watch.get("Код")))
# Добавим недостающее из загруженного:
for offer_id in offer_ids:
stocks.append({"offer_id": offer_id, "stock": 0})
return stocks
def create_prices(watch_remnants, offer_ids):
prices = []
for watch in watch_remnants:
if str(watch.get("Код")) in offer_ids:
price = {
"auto_action_enabled": "UNKNOWN",
"currency_code": "RUB",
"offer_id": str(watch.get("Код")),
"old_price": "0",
"price": price_conversion(watch.get("Цена")),
}
prices.append(price)
return prices
def price_conversion(price: str) -> str:
"""Преобразовать цену. Пример: 5'990.00 руб. -> 5990"""
return re.sub("[^0-9]", "", price.split(".")[0])
def divide(lst: list, n: int):
"""Разделить список lst на части по n элементов"""
for i in range(0, len(lst), n):
yield lst[i : i + n]
async def upload_prices(watch_remnants, client_id, seller_token):
offer_ids = get_offer_ids(client_id, seller_token)
prices = create_prices(watch_remnants, offer_ids)
for some_price in list(divide(prices, 1000)):
update_price(some_price, client_id, seller_token)
return prices
async def upload_stocks(watch_remnants, client_id, seller_token):
offer_ids = get_offer_ids(client_id, seller_token)
stocks = create_stocks(watch_remnants, offer_ids)
for some_stock in list(divide(stocks, 100)):
update_stocks(some_stock, client_id, seller_token)
not_empty = list(filter(lambda stock: (stock.get("stock") != 0), stocks))
return not_empty, stocks
def main():
env = Env()
seller_token = env.str("SELLER_TOKEN")
client_id = env.str("CLIENT_ID")
try:
offer_ids = get_offer_ids(client_id, seller_token)
watch_remnants = download_stock()
# Обновить остатки
stocks = create_stocks(watch_remnants, offer_ids)
for some_stock in list(divide(stocks, 100)):
update_stocks(some_stock, client_id, seller_token)
# Поменять цены
prices = create_prices(watch_remnants, offer_ids)
for some_price in list(divide(prices, 900)):
update_price(some_price, client_id, seller_token)
except requests.exceptions.ReadTimeout:
print("Превышено время ожидания...")
except requests.exceptions.ConnectionError as error:
print(error, "Ошибка соединения")
except Exception as error:
print(error, "ERROR_2")
if __name__ == "__main__":
main()