A Python API client for Pyaterochka store catalog
Project description
Pyaterochka API (not official / не официальный)
Pyaterochka (Пятёрочка) - https://5ka.ru/
Installation / Установка:
- Install package / Установка пакета:
pip install pyaterochka_api
- Debian/Ubuntu Linux: Install dependencies / Установка зависимостей:
sudo apt update && sudo apt install -y libgtk-3-0 libx11-xcb1
- Install browser / Установка браузера:
camoufox fetch
Usage / Использование:
from pyaterochka_api import Pyaterochka
import asyncio
async def main():
async with Pyaterochka(proxy="user:password@host:port", debug=False, autoclose_browser=False, trust_env=False) as API:
# RUS: Вводим геоточку (самого магазина или рядом с ним) и получаем инфу о магазине
# ENG: Enter a geolocation (of the store or near it) and get info about the store
find_store = await API.find_store(longitude=37.63156, latitude=55.73768)
print(f"Store info output: {find_store!s:.100s}...\n")
# RUS: Выводит список всех категорий на сайте
# ENG: Outputs a list of all categories on the site
catalog = await API.categories_list(subcategories=True, mode=API.PurchaseMode.DELIVERY)
print(f"Categories list output: {catalog!s:.100s}...\n")
# RUS: Выводит список всех товаров выбранной категории (ограничение 100 элементов, если превышает - запрашивайте через дополнительные страницы)
# ENG: Outputs a list of all items in the selected category (limiting to 100 elements, if exceeds - request through additional pages)
# Страниц не сущетвует, использовать желаемый лимит (до 499) / Pages do not exist, use the desired limit (up to 499)
items = await API.products_list(catalog[0]['id'], limit=5)
print(f"Items list output: {items!s:.100s}...\n")
# RUS: Выводит информацию о товаре (по его plu - id товара).
# Функция в первый раз достаточно долгая, порядка 5-9 секунды, последующие запросы около 2 секунд (если браузер не был закрыт)
# ENG: Outputs information about the product (by its plu - product id).
# The function is quite long the first time, about 5-9 seconds, subsequent requests take about 2 seconds (if the browser was not closed)
info = await API.product_info(43347)
print(f"Product output: {info["props"]["pageProps"]["props"]['productStore']!s:.100s}...\n")
# RUS: Влияет исключительно на функцию выше (product_info), если включено, то после отработки запроса браузер закроется и кеши очищаются.
# Не рекомендую включать, если вам все же нужно освободить память, лучше использовать API.close(session=False, browser=True)
# ENG: Affects only the function above (product_info), if enabled, the browser will close after the request is processed and caches are cleared.
# 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)
API.autoclose_browser = True
# RUS: Напрямую передается в aiohttp, так же учитывается в браузере. В первую очередь нужен для использования системного `HTTPS_PROXY`.
# Но системный прокси применяется, только если не указали иное напрямую в `API.proxy`.
# ENG: Directly passed to aiohttp, also taken into account in the browser. Primarily needed for using the system `HTTPS_PROXY`.
# But the system proxy is applied only if you did not specify otherwise directly in `API.proxy`.
API.trust_env = True
# RUS: Выводит список последних промо-акций/новостей (можно поставить ограничитель по количеству, опционально)
# ENG: Outputs a list of the latest promotions/news (you can set a limit on the number, optionally)
news = await API.get_news(limit=5)
print(f"News output: {news!s:.100s}...\n")
# RUS: Выводит основной конфиг сайта (очень долгая функция, рекомендую сохранять в файл и переиспользовать)
# ENG: Outputs the main config of the site (large function, recommend to save in a file and re-use it)
print(f"Main config: {await API.get_config()!s:.100s}...\n")
# RUS: Если требуется, можно настроить вывод логов в консоль
# ENG: If required, you can configure the output of logs in the console
API.debug = True
# RUS: Скачивает картинку товара (возвращает BytesIO или None)
# ENG: Downloads the product image (returns BytesIO or None)
image = await API.download_image(url=items['products'][0]['image_links']['normal'][0])
with open(image.name, 'wb') as f:
f.write(image.getbuffer())
# RUS: Можно указать свой таймаут (браузер может его интерпретировать как x2 т.к. там 2 итерации скачивания)
# ENG: You can specify your own timeout (the browser may interpret it as x2 since there are 2 iterations of downloading)
API.timeout = 7
# RUS: Так же как и debug, в рантайме можно переназначить прокси
# ENG: As with debug, you can reassign the proxy in runtime
API.proxy = "user:password@host:port"
# RUS: Изменения происходят сразу же, кроме product_info, т.к. за него отвечает браузер
# ENG: Changes take effect immediately, except for product_info, as it is handled by the browser
await API.rebuild_connection(session=False, browser=True)
await API.product_info(43347)
if __name__ == '__main__':
asyncio.run(main())
Report / Обратная связь
If you have any problems using it /suggestions, do not hesitate to write to the project's GitHub!
Если у вас возникнут проблемы в использовании / пожелания, не стесняйтесь писать на GitHub проекта!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pyaterochka_api-0.1.7.tar.gz.
File metadata
- Download URL: pyaterochka_api-0.1.7.tar.gz
- Upload date:
- Size: 21.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f720c85b976bc98da1d1370671a33d737392e5590217697112a56a153710bf06
|
|
| MD5 |
498e94a33b1f5711ea5ed7f555aef4db
|
|
| BLAKE2b-256 |
60bb3ea09d812d33dbeb816c730a0db557b0e685064828a7027415a77ebf3ca4
|
Provenance
The following attestation bundles were made for pyaterochka_api-0.1.7.tar.gz:
Publisher:
python-publish.yml on Open-Inflation/pyaterochka_api
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pyaterochka_api-0.1.7.tar.gz -
Subject digest:
f720c85b976bc98da1d1370671a33d737392e5590217697112a56a153710bf06 - Sigstore transparency entry: 210366135
- Sigstore integration time:
-
Permalink:
Open-Inflation/pyaterochka_api@307f6a1040ee6bb48a6a02430e3e8164f18b4c93 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/Open-Inflation
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@307f6a1040ee6bb48a6a02430e3e8164f18b4c93 -
Trigger Event:
push
-
Statement type:
File details
Details for the file pyaterochka_api-0.1.7-py3-none-any.whl.
File metadata
- Download URL: pyaterochka_api-0.1.7-py3-none-any.whl
- Upload date:
- Size: 19.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
780821efce0f17975b254d538e29d8eccb15a8fc2dcbc476e1730d03ca188c9c
|
|
| MD5 |
24c350e534e1c12edbfc7bd480fbacd5
|
|
| BLAKE2b-256 |
1585cf762b1d1fb2333447f8d256ae1862685945cbcb892e97eee3aa058fb68d
|
Provenance
The following attestation bundles were made for pyaterochka_api-0.1.7-py3-none-any.whl:
Publisher:
python-publish.yml on Open-Inflation/pyaterochka_api
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pyaterochka_api-0.1.7-py3-none-any.whl -
Subject digest:
780821efce0f17975b254d538e29d8eccb15a8fc2dcbc476e1730d03ca188c9c - Sigstore transparency entry: 210366143
- Sigstore integration time:
-
Permalink:
Open-Inflation/pyaterochka_api@307f6a1040ee6bb48a6a02430e3e8164f18b4c93 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/Open-Inflation
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@307f6a1040ee6bb48a6a02430e3e8164f18b4c93 -
Trigger Event:
push
-
Statement type: