-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathmarket.py
200 lines (175 loc) · 6.8 KB
/
market.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
import datetime
import logging.config
from environs import Env
from seller import download_stock
import requests
from seller import divide, price_conversion
logger = logging.getLogger(__file__)
def get_product_list(page, campaign_id, access_token):
endpoint_url = "https://api.partner.market.yandex.ru/"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
"Accept": "application/json",
"Host": "api.partner.market.yandex.ru",
}
payload = {
"page_token": page,
"limit": 200,
}
url = endpoint_url + f"campaigns/{campaign_id}/offer-mapping-entries"
response = requests.get(url, headers=headers, params=payload)
response.raise_for_status()
response_object = response.json()
return response_object.get("result")
def update_stocks(stocks, campaign_id, access_token):
endpoint_url = "https://api.partner.market.yandex.ru/"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
"Accept": "application/json",
"Host": "api.partner.market.yandex.ru",
}
payload = {"skus": stocks}
url = endpoint_url + f"campaigns/{campaign_id}/offers/stocks"
response = requests.put(url, headers=headers, json=payload)
response.raise_for_status()
response_object = response.json()
return response_object
def update_price(prices, campaign_id, access_token):
endpoint_url = "https://api.partner.market.yandex.ru/"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
"Accept": "application/json",
"Host": "api.partner.market.yandex.ru",
}
payload = {"offers": prices}
url = endpoint_url + f"campaigns/{campaign_id}/offer-prices/updates"
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
response_object = response.json()
return response_object
def get_offer_ids(campaign_id, market_token):
"""Получить артикулы товаров Яндекс маркета"""
page = ""
product_list = []
while True:
some_prod = get_product_list(page, campaign_id, market_token)
product_list.extend(some_prod.get("offerMappingEntries"))
page = some_prod.get("paging").get("nextPageToken")
if not page:
break
offer_ids = []
for product in product_list:
offer_ids.append(product.get("offer").get("shopSku"))
return offer_ids
def create_stocks(watch_remnants, offer_ids, warehouse_id):
# Уберем то, что не загружено в market
stocks = list()
date = str(datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z")
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(
{
"sku": str(watch.get("Код")),
"warehouseId": warehouse_id,
"items": [
{
"count": stock,
"type": "FIT",
"updatedAt": date,
}
],
}
)
offer_ids.remove(str(watch.get("Код")))
# Добавим недостающее из загруженного:
for offer_id in offer_ids:
stocks.append(
{
"sku": offer_id,
"warehouseId": warehouse_id,
"items": [
{
"count": 0,
"type": "FIT",
"updatedAt": date,
}
],
}
)
return stocks
def create_prices(watch_remnants, offer_ids):
prices = []
for watch in watch_remnants:
if str(watch.get("Код")) in offer_ids:
price = {
"id": str(watch.get("Код")),
# "feed": {"id": 0},
"price": {
"value": int(price_conversion(watch.get("Цена"))),
# "discountBase": 0,
"currencyId": "RUR",
# "vat": 0,
},
# "marketSku": 0,
# "shopSku": "string",
}
prices.append(price)
return prices
async def upload_prices(watch_remnants, campaign_id, market_token):
offer_ids = get_offer_ids(campaign_id, market_token)
prices = create_prices(watch_remnants, offer_ids)
for some_prices in list(divide(prices, 500)):
update_price(some_prices, campaign_id, market_token)
return prices
async def upload_stocks(watch_remnants, campaign_id, market_token, warehouse_id):
offer_ids = get_offer_ids(campaign_id, market_token)
stocks = create_stocks(watch_remnants, offer_ids, warehouse_id)
for some_stock in list(divide(stocks, 2000)):
update_stocks(some_stock, campaign_id, market_token)
not_empty = list(
filter(lambda stock: (stock.get("items")[0].get("count") != 0), stocks)
)
return not_empty, stocks
def main():
env = Env()
market_token = env.str("MARKET_TOKEN")
campaign_fbs_id = env.str("FBS_ID")
campaign_dbs_id = env.str("DBS_ID")
warehouse_fbs_id = env.str("WAREHOUSE_FBS_ID")
warehouse_dbs_id = env.str("WAREHOUSE_DBS_ID")
watch_remnants = download_stock()
try:
# FBS
offer_ids = get_offer_ids(campaign_fbs_id, market_token)
# Обновить остатки FBS
stocks = create_stocks(watch_remnants, offer_ids, warehouse_fbs_id)
for some_stock in list(divide(stocks, 2000)):
update_stocks(some_stock, campaign_fbs_id, market_token)
# Поменять цены FBS
upload_prices(watch_remnants, campaign_fbs_id, market_token)
# DBS
offer_ids = get_offer_ids(campaign_dbs_id, market_token)
# Обновить остатки DBS
stocks = create_stocks(watch_remnants, offer_ids, warehouse_dbs_id)
for some_stock in list(divide(stocks, 2000)):
update_stocks(some_stock, campaign_dbs_id, market_token)
# Поменять цены DBS
upload_prices(watch_remnants, campaign_dbs_id, market_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()