From 5218e84acadd2844cc64ea9389d3e4a19b66a731 Mon Sep 17 00:00:00 2001 From: KKlochko Date: Fri, 16 Jun 2023 17:25:16 +0300 Subject: [PATCH] Add CityAPI to get information about city from the server. --- src/api/__init__.py | 0 src/api/v2/__init__.py | 0 src/api/v2/city_api.py | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 src/api/__init__.py create mode 100644 src/api/v2/__init__.py create mode 100644 src/api/v2/city_api.py diff --git a/src/api/__init__.py b/src/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/api/v2/__init__.py b/src/api/v2/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/api/v2/city_api.py b/src/api/v2/city_api.py new file mode 100644 index 0000000..6bf8b41 --- /dev/null +++ b/src/api/v2/city_api.py @@ -0,0 +1,34 @@ +import aiohttp +import asyncio +import ujson + +class CityAPI: + def __init__(self, fetcher, formatter): + """ + Sets needed classes: + + Fetcher (ApiFetcher) - class that will fetch data. + Format (AbstractFormat) - class that will format response data. + """ + self.__fetcher, self.__formatter = fetcher, formatter + + async def get_objects(self) -> dict: + endpoint = "/api/v2/cities" + + status, json_data = await self.__fetcher.fetch_json(endpoint) + + if status == 200: + return {"ok": json_data} + + return {"error": "Сталася помилка, спробуйте пізніше."} + + async def get_objects_message(self) -> str: + response = await self.get_objects() + + match response: + case {"ok": json_data}: + return self.__formatter.format_all(json_data) + + case {"error": error_message}: + return error_message +