Skip to content

Commit d85d2db

Browse files
committed
complite docs
1 parent 6b68ef6 commit d85d2db

7 files changed

Lines changed: 213 additions & 147 deletions

File tree

README.md

Lines changed: 80 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -1,116 +1,106 @@
1-
# В данный момент разработчики обновили антибота, библиотека переписывается!
1+
<div align="center">
22

3-
# Pyaterochka API *(not official / не официальный)*
3+
# Pyaterochka API *(not official)*
44

5-
Pyaterochka (Пятёрочка) - https://5ka.ru/
6-
7-
[![GitHub Actions](https://github.com/Open-Inflation/pyaterochka_api/workflows/API%20Tests%20Daily/badge.svg)](https://github.com/Open-Inflation/pyaterochka_api/actions?query=workflow%3A"API+Tests+Daily?query=branch%3Amain")
5+
![Tests last run (ISO)](https://img.shields.io/badge/dynamic/json?label=Tests%20last%20run&query=%24.workflow_runs%5B0%5D.updated_at&url=https%3A%2F%2Fapi.github.com%2Frepos%2FOpen-Inflation%2Fpyaterochka_api%2Factions%2Fworkflows%2Ftests.yml%2Fruns%3Fper_page%3D1%26status%3Dcompleted&logo=githubactions&cacheSeconds=300)
6+
[![Tests](https://github.com/Open-Inflation/pyaterochka_api/actions/workflows/tests.yml/badge.svg)](https://github.com/Open-Inflation/pyaterochka_api/actions/workflows/tests.yml)
87
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pyaterochka_api)
98
![PyPI - Package Version](https://img.shields.io/pypi/v/pyaterochka_api?color=blue)
109
[![PyPI - Downloads](https://img.shields.io/pypi/dm/pyaterochka_api?label=PyPi%20downloads)](https://pypi.org/project/pyaterochka-api/)
11-
[![API Documentation](https://img.shields.io/badge/API-Documentation-blue)](https://open-inflation.github.io/pyaterochka_api/)
10+
[![License](https://img.shields.io/github/license/Open-Inflation/pyaterochka_api)](https://github.com/Open-Inflation/pyaterochka_api/blob/main/LICENSE)
1211
[![Discord](https://img.shields.io/discord/792572437292253224?label=Discord&labelColor=%232c2f33&color=%237289da)](https://discord.gg/UnJnGHNbBp)
1312
[![Telegram](https://img.shields.io/badge/Telegram-24A1DE)](https://t.me/miskler_dev)
1413

1514

15+
Pyaterochka (Пятёрочка) - https://5ka.ru/
16+
17+
**[⭐ Star us on GitHub](https://github.com/Open-Inflation/pyaterochka_api)** | **[📚 Read the Docs](https://open-inflation.github.io/pyaterochka_api/quick_start)** | **[🐛 Report Bug](https://github.com/Open-Inflation/pyaterochka_api/issues)**
18+
19+
### Принцип работы
20+
21+
</div>
22+
23+
> Библиотека полностью повторяет сетевую работу обычного пользователя на сайте.
24+
25+
<div align="center">
26+
27+
## Usage:
28+
29+
</div>
1630

17-
## Installation / Установка:
18-
1. Install package / Установка пакета:
1931
```bash
2032
pip install pyaterochka_api
21-
```
22-
2. ***Debian/Ubuntu Linux***: Install dependencies / Установка зависимостей:
23-
```bash
24-
sudo apt update && sudo apt install -y libgtk-3-0 libx11-xcb1
25-
```
26-
3. Install browser / Установка браузера:
27-
```bash
28-
camoufox fetch
33+
python -m camoufox fetch
2934
```
3035

31-
### Usage / Использование:
3236
```py
33-
from pyaterochka_api import Pyaterochka, PurchaseMode
37+
from pyaterochka_api import PyaterochkaAPI
3438
import asyncio
35-
39+
from PIL import Image
3640

3741
async def main():
38-
async with Pyaterochka(proxy="user:password@host:port", debug=False, autoclose_browser=False, trust_env=False) as API:
39-
# RUS: Вводим геоточку (самого магазина или рядом с ним) и получаем инфу о магазине
40-
# ENG: Enter a geolocation (of the store or near it) and get info about the store
41-
find_store = await API.find_store(longitude=37.63156, latitude=55.73768)
42-
print(f"Store info output: {find_store!s:.100s}...\n")
43-
44-
# RUS: Выводит список всех категорий на сайте
45-
# ENG: Outputs a list of all categories on the site
46-
catalog = await API.categories_list(subcategories=True, mode=API.PurchaseMode.DELIVERY)
47-
print(f"Categories list output: {catalog!s:.100s}...\n")
48-
49-
# RUS: Выводит список всех товаров выбранной категории (ограничение 100 элементов, если превышает - запрашивайте через дополнительные страницы)
50-
# ENG: Outputs a list of all items in the selected category (limiting to 100 elements, if exceeds - request through additional pages)
51-
# Страниц не сущетвует, использовать желаемый лимит (до 499) / Pages do not exist, use the desired limit (up to 499)
52-
items = await API.products_list(catalog[0]['id'], limit=5)
53-
print(f"Items list output: {items!s:.100s}...\n")
54-
55-
# RUS: Выводит информацию о товаре (по его plu - id товара).
56-
# Функция в первый раз достаточно долгая, порядка 5-9 секунды, последующие запросы около 2 секунд (если браузер не был закрыт)
57-
# ENG: Outputs information about the product (by its plu - product id).
58-
# The function is quite long the first time, about 5-9 seconds, subsequent requests take about 2 seconds (if the browser was not closed)
59-
info = await API.product_info(43347)
60-
print(f"Product output: {info["props"]["pageProps"]["props"]['productStore']!s:.100s}...\n")
61-
62-
# RUS: Влияет исключительно на функцию выше (product_info), если включено, то после отработки запроса браузер закроется и кеши очищаются.
63-
# Не рекомендую включать, если вам все же нужно освободить память, лучше использовать API.close(session=False, browser=True)
64-
# ENG: Affects only the function above (product_info), if enabled, the browser will close after the request is processed and caches are cleared.
65-
# I do not recommend enabling it, if you still need to free up memory, it is better to use API.close(session=False, browser=True)
66-
API.autoclose_browser = True
67-
68-
# RUS: Напрямую передается в aiohttp, так же учитывается в браузере. В первую очередь нужен для использования системного `HTTPS_PROXY`.
69-
# Но системный прокси применяется, только если не указали иное напрямую в `API.proxy`.
70-
# ENG: Directly passed to aiohttp, also taken into account in the browser. Primarily needed for using the system `HTTPS_PROXY`.
71-
# But the system proxy is applied only if you did not specify otherwise directly in `API.proxy`.
72-
API.trust_env = True
73-
74-
# RUS: Выводит список последних промо-акций/новостей (можно поставить ограничитель по количеству, опционально)
75-
# ENG: Outputs a list of the latest promotions/news (you can set a limit on the number, optionally)
76-
news = await API.get_news(limit=5)
77-
print(f"News output: {news!s:.100s}...\n")
78-
79-
# RUS: Если требуется, можно настроить вывод логов в консоль
80-
# ENG: If required, you can configure the output of logs in the console
81-
API.debug = True
82-
83-
# RUS: Скачивает картинку товара (возвращает BytesIO или None)
84-
# ENG: Downloads the product image (returns BytesIO or None)
85-
image = await API.download_image(url=items['products'][0]['image_links']['normal'][0])
86-
with open(image.name, 'wb') as f:
87-
f.write(image.getbuffer())
88-
89-
# RUS: Можно указать свой таймаут (браузер может его интерпретировать как x2 т.к. там 2 итерации скачивания)
90-
# ENG: You can specify your own timeout (the browser may interpret it as x2 since there are 2 iterations of downloading)
91-
API.timeout = 7
92-
93-
# RUS: Так же как и debug, в рантайме можно переназначить прокси
94-
# ENG: As with debug, you can reassign the proxy in runtime
95-
API.proxy = "user:password@host:port"
96-
# RUS: Изменения происходят сразу же, кроме product_info, т.к. за него отвечает браузер
97-
# ENG: Changes take effect immediately, except for product_info, as it is handled by the browser
98-
await API.rebuild_connection(session=False, browser=True)
99-
await API.product_info(43347)
100-
101-
102-
if __name__ == '__main__':
42+
async with PyaterochkaAPI() as api:
43+
44+
# 1. Получение информации о текущем выбранном магазине доставки
45+
store_info = await api.delivery_panel_store()
46+
sap_code = store_info["selectedStore"]["sapCode"]
47+
print(f"SAP код выбранного магазина: {sap_code}\n")
48+
49+
# 2. Получение списка всех категорий
50+
tree_resp = await api.Catalog.tree(sap_code_store_id=sap_code)
51+
categories_data = tree_resp.json()
52+
first_category = categories_data[0]
53+
print(f"Первая категория: {first_category['name']!s:.50s}...\n")
54+
55+
# 3. Получение списка товаров в первой категории
56+
products_resp = await api.Catalog.products_list(
57+
category_id=first_category["id"], sap_code_store_id=sap_code
58+
)
59+
products_data = products_resp.json()
60+
first_product_plu = products_data["products"][0]["plu"]
61+
print(f"Первый товар (PLU): {first_product_plu}\n")
62+
63+
# 4. Получение подробной информации о первом товаре
64+
product_info_resp = await api.Catalog.Product.info(
65+
sap_code_store_id=sap_code, plu_id=first_product_plu
66+
)
67+
product_info_data = product_info_resp.json()
68+
print(f"Название первого товара: {product_info_data['name']!s:.50s}...\n")
69+
70+
# 5. Примеры использования геолокации
71+
72+
# Поиск адресов по запросу
73+
suggest_resp = await api.Geolocation.suggest("москва")
74+
print(f"Предложения по геолокации для 'москва': {suggest_resp.json()['results'][0]['address']['formatted_address']!s:.50s}...\n")
75+
76+
# Определение текущей геолокации
77+
geocode_resp = await api.Geolocation.geocode()
78+
pos: str = geocode_resp.json()["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["Point"]["pos"]
79+
longitude, latitude = pos.split(" ")
80+
print(f"Выбранная геолокация (долгота, широта): {longitude}, {latitude}\n")
81+
82+
# 6. Скачивание изображения (на примере изображения первой подкатегории)
83+
image_link = first_category["categories"][0]["image_link"]
84+
image_stream = await api.General.download_image(image_link)
85+
86+
# Пример обработки изображения с помощью PIL
87+
with Image.open(image_stream) as img:
88+
print(f"Изображение скачано. Формат: {img.format}. Размер: {img.size}\n")
89+
# img.save("first_category_image.png") # Можно сохранить локально
90+
91+
# Запуск асинхронной функции main
92+
if __name__ == "__main__":
10393
asyncio.run(main())
10494
```
10595

106-
### API Documentation / Документация API
96+
Для более подробной информации смотрите референсы [документации](https://open-inflation.github.io/pyaterochka_api/quick_start).
10797

108-
Автоматически сгенерированная документация API доступна по ссылке: [API Documentation](https://open-inflation.github.io/pyaterochka_api/)
98+
---
10999

110-
Документация содержит подробную структуру всех ответов сервера в виде схем (на базе тестов).
100+
<div align="center">
111101

112-
### Report / Обратная связь
102+
### Report
113103

114-
If you have any problems using it /suggestions, do not hesitate to write to the [project's GitHub](https://github.com/Open-Inflation/pyaterochka_api/issues)!
104+
If you have any problems using it / suggestions, do not hesitate to write to the [project's GitHub](https://github.com/Open-Inflation/pyaterochka_api/issues)!
115105

116-
Если у вас возникнут проблемы в использовании / пожелания, не стесняйтесь писать на [GitHub проекта](https://github.com/Open-Inflation/pyaterochka_api/issues)!
106+
</div>

docs/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def _get_version() -> str:
3838
pass
3939
# 3) fallback: import from package (may fail on RTD without deps)
4040
try:
41-
from chizhik_api import __version__ # type: ignore
41+
from pyaterochka_api import __version__ # type: ignore
4242
return __version__
4343
except Exception:
4444
return "0.0.0"

docs/source/pyaterochka_api.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
chizhik\_api package
1+
pyaterochka\_api package
22
====================
33

44
.. automodule:: pyaterochka_api

0 commit comments

Comments
 (0)