From f38d704f7ed30aa2dc2e89eb09e3f42f45ec078b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Fri, 10 Jun 2022 15:06:15 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82=D0=BE?= =?UTF-8?q?=D1=80=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=B8=20=D1=84?= =?UTF-8?q?=D0=BE=D1=80=D0=BC=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE=D1=81=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Упростил формирование запросов. Совсем вылетела из головы `range`. --- solution.py | 46 ++++++++++++++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/solution.py b/solution.py index 285ed47..8810b32 100644 --- a/solution.py +++ b/solution.py @@ -59,24 +59,34 @@ async def get_records_count(session, server) -> int: return count -async def get_tasks(cfg: Config, session: aiohttp.ClientSession, count, body) -> list: - """Вернет список запросов к API. +async def get_tasks( + url: str, portion: int, count: int, session: aiohttp.ClientSession, body: dict +) -> List[Task]: + """Вернет список задач с запросами к API. Функция не ограничивает кол-во запросов, это нужно сделать до вызова, чтобы передать корректный `session`. + + Parameters + ---------- + url : str + Куда слать запрос. Ожидается "server/get" + portion : int + Сколько записей запрашивать за раз + count : int + Общее количество записей + session : aiohttp.ClientSession + Объект сессии, создается в уровне выше, с одним объектом + меньше накладных расходов на каждый запрос. + body : json + Json для запроса. """ tasks: List[Task] = [] - offset = 0 - url = f"{cfg.central_host_url}/get" - for _ in range(count // cfg.request_portion + 1): - if offset < count: - print(f"{offset=}") - tasks.append(asyncio.create_task(session.get(url, json=body))) - offset += cfg.request_portion - body["offset"] = offset + for offset in range(0, count, portion): + tasks.append(asyncio.create_task(session.get(url, json=body))) + body["offset"] = offset - print(f"{count=}") return tasks @@ -87,14 +97,19 @@ async def send_async_request(cfg: Config, json_body: dict) -> None: # ограничим одновременное число запросов conn = aiohttp.TCPConnector(limit=cfg.requests_count) + url = cfg.central_host_url + portion = cfg.request_portion + async with aiohttp.ClientSession(connector=conn) as session: - # всего записей в базе - count = await get_records_count(session, cfg.central_host_url) + # получаем количесвто записей + count = await get_records_count(session, url) - tasks = await get_tasks(cfg, session, count, json_body) + tasks = await get_tasks(f"{url}/get", portion, count, session, json_body) responses = await asyncio.gather(*tasks) + # Пройдемся по ответам на запросы, запишем файлы конфига для + # каждого respone. Каждый response содержит portion или меньше хостов for response in responses: resp = await response.json() hosts = [i["hostname"] for i in resp.get("result")] @@ -102,8 +117,7 @@ async def send_async_request(cfg: Config, json_body: dict) -> None: def read_config(path_to_conf_file: str, section: str = "Main") -> Config: - """ - Считать конфиг с помощью `configparser`. + """Считать конфиг с помощью `configparser`. Parameters ----------