From db62063d5ab2b6e9f68b0a8e7843e858054e8f8a Mon Sep 17 00:00:00 2001 From: KKlochko Date: Fri, 16 Jun 2023 17:15:46 +0300 Subject: [PATCH] Add ApiFetcher to make requests to the server. --- src/fetcher/__init__.py | 0 src/fetcher/v2/__init__.py | 0 src/fetcher/v2/api_fetcher.py | 37 +++++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 src/fetcher/__init__.py create mode 100644 src/fetcher/v2/__init__.py create mode 100644 src/fetcher/v2/api_fetcher.py diff --git a/src/fetcher/__init__.py b/src/fetcher/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/fetcher/v2/__init__.py b/src/fetcher/v2/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/fetcher/v2/api_fetcher.py b/src/fetcher/v2/api_fetcher.py new file mode 100644 index 0000000..801ea46 --- /dev/null +++ b/src/fetcher/v2/api_fetcher.py @@ -0,0 +1,37 @@ +import aiohttp +import asyncio +import ujson + +class ApiFetcher: + def __init__(self, base_url: str, session): + self.__base_url = base_url + self.__session = session + + async def fetch_json(self, endpoint: str) -> (int, dict): + """ + Gets a JSON payload from the API endpoint. + + url (str): the JSON payload will be gotten to the URL. + context (dict): the dictionary that will be sended as a JSON payload. + """ + url = f"{self.__base_url}{endpoint}" + + async with self.__session.get(url) as response: + status = response.status + json_data = await response.json() + return (status, json_data) + + async def send_json(self, endpoint: str, context: dict) -> (int, dict): + """ + Sends a JSON payload to the API endpoint. + + url (str): the JSON payload will be sent to the API endpoint. + context (dict): the dictionary that will be sent as a JSON payload. + """ + url = f"{self.__base_url}{endpoint}" + + async with self.__session.get(url) as session: + await session.post(url, json=context) + json_data = await session.json() + return (session.status, json_data) +