Skip to content

Commit

Permalink
Move functions to utils.py
Browse files Browse the repository at this point in the history
  • Loading branch information
bieniu committed Apr 24, 2024
1 parent ec57eea commit 77e76fd
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 19 deletions.
25 changes: 9 additions & 16 deletions imgw_pib/__init__.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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__)

Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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",
)
Expand Down Expand Up @@ -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",
)
Expand All @@ -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",
)
Expand All @@ -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
19 changes: 19 additions & 0 deletions imgw_pib/utils.py
Original file line number Diff line number Diff line change
@@ -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
6 changes: 3 additions & 3 deletions tests/snapshots/test_init.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -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)',
Expand Down Expand Up @@ -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)',
Expand Down Expand Up @@ -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)',
Expand Down

0 comments on commit 77e76fd

Please sign in to comment.