Skip to content

Commit 3b18281

Browse files
committed
almost complite testing
1 parent ef105e7 commit 3b18281

28 files changed

Lines changed: 6798 additions & 561 deletions

main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ async def main():
77
async with PyaterochkaAPI(headless=False) as API:
88
# RUS: Выводит активные предложения магазина
99
# ENG: Outputs active offers of the store
10-
pprint((await API.Catalog.tree(sap_code_store_id="35XY", subcategories=False)).json())
10+
tree = (await API.Catalog.tree(sap_code_store_id="35XY", subcategories=False)).json()
1111

1212
import asyncio
1313
asyncio.run(main())

pyaterochka_api/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from .manager import PyaterochkaAPI
2-
from .enums import PurchaseMode
2+
from .enums import PurchaseMode, Sorting
33

44
__version__ = "0.2.0.1"
5-
__all__ = ['PyaterochkaAPI', 'PurchaseMode']
5+
__all__ = ['PyaterochkaAPI', 'PurchaseMode', 'Sorting']

pyaterochka_api/endpoints/catalog.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -45,16 +45,16 @@ async def tree(self,
4545
"""
4646

4747
request_url = f"{self._parent.CATALOG_URL}/catalog/v2/stores/{sap_code_store_id}/categories?mode={mode.value}&include_restrict={include_restrict}&include_subcategories={1 if subcategories else 0}"
48-
return await self._parent._request(method=HttpMethod.GET, url=request_url)
48+
return await self._parent._request(method=HttpMethod.GET, url=request_url, add_unstandard_headers=True)
4949

5050
async def tree_extended(self,
5151
sap_code_store_id: str,
5252
category_id: str,
5353
include_restrict: bool = True,
5454
mode: PurchaseMode = PurchaseMode.STORE) -> FetchResponse:
5555
"""Расширенное представление категории и её подкатегорий."""
56-
request_url = f"{self._parent.CATALOG_URL}/api/catalog/v2/stores/{sap_code_store_id}/categories/{category_id}/extended?mode={mode.value}&include_restrict={str(include_restrict).lower()}"
57-
return await self._parent._request(method=HttpMethod.GET, url=request_url)
56+
request_url = f"{self._parent.CATALOG_URL}/catalog/v2/stores/{sap_code_store_id}/categories/{category_id}/extended?mode={mode.value}&include_restrict={str(include_restrict).lower()}"
57+
return await self._parent._request(method=HttpMethod.GET, url=request_url, add_unstandard_headers=True)
5858

5959
async def search(self,
6060
sap_code_store_id: str,
@@ -64,8 +64,8 @@ async def search(self,
6464
limit: int = 12) -> FetchResponse:
6565
"""Поиск по товарам И категориям."""
6666
q = urllib.parse.quote(query)
67-
request_url = f"{self._parent.CATALOG_URL}/api/catalog/v3/stores/{sap_code_store_id}/search?mode={mode.value}&include_restrict={str(include_restrict).lower()}&q={q}&limit={limit}"
68-
return await self._parent._request(method=HttpMethod.GET, url=request_url)
67+
request_url = f"{self._parent.CATALOG_URL}/catalog/v3/stores/{sap_code_store_id}/search?mode={mode.value}&include_restrict={str(include_restrict).lower()}&q={q}&limit={limit}"
68+
return await self._parent._request(method=HttpMethod.GET, url=request_url, add_unstandard_headers=True)
6969

7070
async def products_list(
7171
self,
@@ -84,7 +84,7 @@ async def products_list(
8484
Args:
8585
category_id (str): The ID of the (sub)category.
8686
mode (PurchaseMode, optional): The purchase mode to use. Defaults to PurchaseMode.STORE.
87-
sap_code_store_id (str, optional): The store ID (official name in API is "sap_code") to use. Defaults to "{self.DEFAULT_STORE_ID}". This lib not support search ID stores.
87+
sap_code_store_id (str, optional): The store ID (official name in API is "sap_code") to use. This lib not support search ID stores.
8888
limit (int, optional): The maximum number of products to retrieve. Defaults to 30. Must be between 1 and 499.
8989
9090
Returns:
@@ -107,7 +107,7 @@ async def products_list(
107107
encoded_brands = [f'brands={urllib.parse.quote(brand)}' for brand in brands]
108108
request_url += "&" + '&&'.join(encoded_brands)
109109

110-
return await self._parent._request(method=HttpMethod.GET, url=request_url)
110+
return await self._parent._request(method=HttpMethod.GET, url=request_url, add_unstandard_headers=True)
111111

112112
async def products_line(
113113
self,
@@ -118,8 +118,8 @@ async def products_line(
118118
order_by: Sorting = Sorting.POPULARITY
119119
) -> FetchResponse:
120120
"""Рекомендованные товары \"что интересного?\"."""
121-
request_url = f"https://5d.5ka.ru/api/catalog/v1/stores/{sap_code_store_id}/categories/{category_id}/products_line?mode={mode.value}&include_restrict={str(include_restrict).lower()}&order_by={order_by.value}"
122-
return await self._parent._request(method=HttpMethod.GET, url=request_url)
121+
request_url = f"{self._parent.CATALOG_URL}/catalog/v1/stores/{sap_code_store_id}/categories/{category_id}/products_line?mode={mode.value}&include_restrict={str(include_restrict).lower()}&order_by={order_by.value}"
122+
return await self._parent._request(method=HttpMethod.GET, url=request_url, add_unstandard_headers=True)
123123

124124

125125
class ProductService:
@@ -147,4 +147,4 @@ async def info(
147147
"""
148148

149149
request_url = f"{self._parent.CATALOG_URL}/catalog/v2/stores/{sap_code_store_id}/products/{plu_id}?mode={mode.value}&include_restrict={str(include_restrict).lower()}"
150-
return await self._parent._request(method=HttpMethod.GET, url=request_url)
150+
return await self._parent._request(method=HttpMethod.GET, url=request_url, add_unstandard_headers=True)

pyaterochka_api/endpoints/geolocation.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,12 @@ async def find_store(self, longitude: float, latitude: float) -> FetchResponse:
3232
"""
3333

3434
request_url = f"{self._parent.CATALOG_URL}/orders/v1/orders/stores/?lon={longitude}&lat={latitude}"
35-
return await self._parent._request(method=HttpMethod.GET, url=request_url)
35+
return await self._parent._request(method=HttpMethod.GET, url=request_url, add_unstandard_headers=True)
3636

3737
async def suggest(self, query: str) -> FetchResponse:
3838
"""Начинайте вводить адрес, он предложит точные варианты"""
3939
request_url = f"{self._parent.CATALOG_URL}/maps/suggest/?text={urllib.parse.quote(query)}"
40-
return await self._parent._request(method=HttpMethod.GET, url=request_url)
40+
return await self._parent._request(method=HttpMethod.GET, url=request_url, add_unstandard_headers=True)
4141

4242
async def geocode(self,
4343
country: str = "Россия",
@@ -51,4 +51,4 @@ async def geocode(self,
5151
string = urllib.parse.quote(", ".join(tup))
5252

5353
request_url = f"{self._parent.MAIN_SITE_URL}/api/maps/geocode/?geocode={string}"
54-
return await self._parent._request(method=HttpMethod.GET, url=request_url)
54+
return await self._parent._request(method=HttpMethod.GET, url=request_url, add_unstandard_headers=True)

pyaterochka_api/manager.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from dataclasses import dataclass, field
55
from typing import Any
66
import json
7-
7+
from collections import defaultdict
88
from camoufox.async_api import AsyncCamoufox
99
from human_requests import HumanBrowser, HumanContext, HumanPage
1010
from human_requests.abstraction import FetchResponse, HttpMethod, Proxy
@@ -50,7 +50,7 @@ class PyaterochkaAPI:
5050
page: HumanPage = field(init=False, repr=False)
5151
"""Внутренний страница сессии браузера"""
5252

53-
unstandard_headers: dict[str, str] = {}
53+
unstandard_headers: dict[str, str] = field(init=False, repr=False)
5454
"""Список нестандартных заголовков пойманных при инициализации"""
5555

5656
Geolocation: ClassGeolocation = field(init=False)
@@ -116,8 +116,17 @@ async def _warmup(self) -> None:
116116
timeout_ms=self.timeout_ms
117117
)
118118

119-
result = await sniffer.complete()
120-
self.unstandard_headers = result.get("https://5d.5ka.ru")
119+
result_sniffer = await sniffer.complete()
120+
# Результат: {заголовок: [уникальные значения]}
121+
result = defaultdict(set)
122+
123+
# Проходим по всем URL в 'request'
124+
for _url, headers in result_sniffer['request'].items():
125+
for header, values in headers.items():
126+
result[header].update(values) # добавляем значения, set уберёт дубли
127+
128+
# Преобразуем set обратно в list
129+
self.unstandard_headers = {k: list(v) for k, v in result.items()}
121130

122131
async def __aexit__(self, *exc):
123132
"""Выход из контекстного менеджера с закрытием сессии."""

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,5 @@ version = {attr = "pyaterochka_api.__version__"}
5353
pythonpath = ["."]
5454
testpaths = ["tests"]
5555
python_files = ["*_test.py", "*_tests.py"]
56+
anyio_mode = "auto"
57+
addopts = "-v --tb=short --disable-warnings"

0 commit comments

Comments
 (0)