From 77e76fdbeafa5a2f1528bc785d84825cf83fb662 Mon Sep 17 00:00:00 2001 From: Maciej Bieniek <478555+bieniu@users.noreply.github.com> Date: Wed, 24 Apr 2024 16:50:14 +0200 Subject: [PATCH] Move functions to utils.py --- imgw_pib/__init__.py | 25 +++++++++---------------- imgw_pib/utils.py | 19 +++++++++++++++++++ tests/snapshots/test_init.ambr | 6 +++--- 3 files changed, 31 insertions(+), 19 deletions(-) create mode 100644 imgw_pib/utils.py diff --git a/imgw_pib/__init__.py b/imgw_pib/__init__.py index c79f5dc..da16fa9 100644 --- a/imgw_pib/__init__.py +++ b/imgw_pib/__init__.py @@ -1,7 +1,6 @@ """Python wrapper for IMGW-PIB API.""" import logging -from datetime import UTC, datetime from http import HTTPStatus from typing import Any, Self @@ -16,6 +15,7 @@ ) from .exceptions import ApiError from .model import ApiNames, HydrologicalData, SensorData, Units, WeatherData +from .utils import gen_station_name, get_datetime _LOGGER = logging.getLogger(__name__) @@ -112,9 +112,9 @@ async def update_hydrological_stations(self: Self) -> None: stations_data = await self._http_request(url) self._hydrological_station_list = { - station[ - ApiNames.STATION_ID - ]: f"{station[ApiNames.RIVER]} ({station[ApiNames.STATION]})" + station[ApiNames.STATION_ID]: gen_station_name( + station[ApiNames.STATION], station[ApiNames.RIVER] + ) for station in stations_data } @@ -157,7 +157,8 @@ async def _http_request(self: Self, url: str) -> Any: # noqa: ANN401 return await response.json() - def _parse_weather_data(self: Self, data: dict[str, Any]) -> WeatherData: + @staticmethod + def _parse_weather_data(data: dict[str, Any]) -> WeatherData: """Parse weather data.""" temperature = data[ApiNames.TEMPERATURE] temperature_sensor = SensorData( @@ -195,7 +196,7 @@ def _parse_weather_data(self: Self, data: dict[str, Any]) -> WeatherData: value=float(pressure) if pressure is not None else None, unit=Units.HPA.value if pressure is not None else None, ) - measurement_date = self._get_datetime( + measurement_date = get_datetime( f"{data[ApiNames.MEASUREMENT_DATE]} {data[ApiNames.MEASUREMENT_TIME]}", "%Y-%m-%d %H", ) @@ -225,7 +226,7 @@ def _parse_hydrological_data(self: Self, data: dict[str, Any]) -> HydrologicalDa value=float(water_level) if water_level is not None else None, unit=Units.CENTIMETERS.value if water_level is not None else None, ) - water_level_measurement_date = self._get_datetime( + water_level_measurement_date = get_datetime( data[ApiNames.WATER_LEVEL_MEASUREMENT_DATE], "%Y-%m-%d %H:%M:%S", ) @@ -249,7 +250,7 @@ def _parse_hydrological_data(self: Self, data: dict[str, Any]) -> HydrologicalDa value=float(water_temperature) if water_temperature is not None else None, unit=Units.CELSIUS.value if water_temperature is not None else None, ) - water_temperature_measurement_date = self._get_datetime( + water_temperature_measurement_date = get_datetime( data[ApiNames.WATER_TEMPERATURE_MEASUREMENT_DATE], "%Y-%m-%d %H:%M:%S", ) @@ -265,11 +266,3 @@ def _parse_hydrological_data(self: Self, data: dict[str, Any]) -> HydrologicalDa water_level_measurement_date=water_level_measurement_date, water_temperature_measurement_date=water_temperature_measurement_date, ) - - @staticmethod - def _get_datetime(date_time: str, date_format: str) -> datetime | None: - """Get datetime object from date-time string.""" - try: - return datetime.strptime(date_time, date_format).replace(tzinfo=UTC) - except (TypeError, ValueError): - return None diff --git a/imgw_pib/utils.py b/imgw_pib/utils.py new file mode 100644 index 0000000..9ecc12c --- /dev/null +++ b/imgw_pib/utils.py @@ -0,0 +1,19 @@ +"""Utils for imgw-pib.""" + +from datetime import UTC, datetime + + +def gen_station_name(station: str, river: str) -> str: + """Generate station name.""" + if river == "-": + return station + + return f"{river} ({station})" + + +def get_datetime(date_time: str, date_format: str) -> datetime | None: + """Get datetime object from date-time string.""" + try: + return datetime.strptime(date_time, date_format).replace(tzinfo=UTC) + except (TypeError, ValueError): + return None diff --git a/tests/snapshots/test_init.ambr b/tests/snapshots/test_init.ambr index 58c5e28..eaef270 100644 --- a/tests/snapshots/test_init.ambr +++ b/tests/snapshots/test_init.ambr @@ -86,7 +86,7 @@ '149200310': 'Biała (Grybów)', '149200320': 'Biała (Koszyce Wielkie)', '149200330': 'Biała (Ciężkowice)', - '149200360': '- (Lipnica Murowana)', + '149200360': 'Lipnica Murowana', '149200370': 'Uszwica (Brzesko-Okocim)', '149200480': 'Stradomka (Łapanów)', '149200510': 'Uszwica (Brzesko-Miasto)', @@ -208,7 +208,7 @@ '150180280': 'Ruda (Rybnik Gotartowice)', '150190010': 'Brynica (Brynica)', '150190060': 'Gostynia (Bojszowy)', - '150190070': '- (Szabelnia)', + '150190070': 'Szabelnia', '150190080': 'Czarna Przemsza (Radocha)', '150190100': 'Biała Przemsza (Niwka)', '150190120': 'Czarna Przemsza (Przeczyce)', @@ -574,7 +574,7 @@ '154180090': 'Zatoka Pucka (Puck)', '154180100': 'Bałtyk (Władysławowo)', '154180120': 'Bałtyk (Gdynia)', - '154180140': '- (Gdańsk)', + '154180140': 'Gdańsk', '154180150': 'Wisła (Tczew)', '154180160': 'Martwa Wisła (Sobieszewo)', '154180170': 'Motława (Wiślina)',