Files
gallery/gallery/painting/openweather/api.py
T

77 lines
2.9 KiB
Python

import datetime
from itertools import groupby
from os import environ
from aiocache import cached
from gallery.sketch.weather.api import WeatherApi
from gallery.sketch.weather.model import Location, WeatherResponse, WeatherValue
from gallery.sketch.weather.util import merge_weather_values
from gallery.util import TimeUnit
from . import PROVIDER
from .openweather import Location as OpenWeatherLocation
from .openweather import OpenWeather
from .parser import OpenWeatherForecastParser, OpenWeatherLocationParser
class OpenWeatherApi(WeatherApi[OpenWeather]):
PROVIDER = PROVIDER
forecast_parser = OpenWeatherForecastParser()
location_parser = OpenWeatherLocationParser()
def _build_source(self) -> OpenWeather:
return OpenWeather(environ["OPENWEATHER_KEY"])
@classmethod
def _parse_location(cls, location_id: str) -> tuple[float, float]:
return tuple(map(float, location_id.split(":", maxsplit=2)))
@cached(
key_builder=lambda fun, self, location_id: f"api.weather.{self.provider}.source.{location_id}.location",
alias="redis",
ttl=TimeUnit.DAY,
)
async def _get_location(self, location_id: str) -> OpenWeatherLocation:
return await self.source.get_location(*self._parse_location(location_id))
@cached(
key_builder=lambda fun, self, location_id: f"api.weather.{self.provider}.source.{location_id}.forecast",
alias="redis",
ttl=TimeUnit.HOUR,
)
async def _get_location_forecast(self, location_id: str) -> list[WeatherValue]:
content = await self.source.get_forecast(*self._parse_location(location_id))
return self.forecast_parser.parse(content)
async def find_locations(self, query: str) -> list[Location]:
content = await self.source.find_locations(query)
return self.location_parser.parse(content)
async def get_day(self, location_id: str, date: datetime.date) -> WeatherResponse:
location: OpenWeatherLocation = await self._get_location(location_id)
values = [value for value in await self._get_location_forecast(location_id) if value.date.date() == date]
return WeatherResponse(
location=location.name,
date=date,
period="day",
values=values,
)
async def get_days(self, location_id: str, days: int) -> WeatherResponse:
location: OpenWeatherLocation = await self._get_location(location_id)
values = [
merge_weather_values(datetime.datetime.combine(k, datetime.datetime.min.time()), list(g))
for k, g in groupby(
sorted(await self._get_location_forecast(location_id), key=lambda item: item.date.date()),
lambda item: item.date.date(),
)
]
return WeatherResponse(
location=location.name,
date=datetime.date.today(),
period="days",
values=list(sorted(values, key=lambda item: item.date)),
)