feat: split to weather and gismeteo modules

This commit is contained in:
2024-07-26 11:02:01 +03:00
parent c9e52c43a9
commit 848b6bd9ba
28 changed files with 157 additions and 108 deletions

View File

@@ -1,27 +1,18 @@
import datetime
from typing import Any, Dict, List, NamedTuple
from typing import Any, Dict, List
import aiohttp
from bs4 import BeautifulSoup
from . import dateutil
from weather.api import WeatherApi
from weather.model import WeatherResponse, WeatherValue
from . import datehelp
from .location import LOCATION_BUNDLE
from .parser import ROW_PARSERS, ONE_DAY_PARSER
from .parser import LOCATION_PARSER, ONE_DAY_PARSER, ROW_PARSERS
class WeatherValue(NamedTuple):
date: datetime.datetime
cloudness: str
temperature: int
wind_speed: int
wind_gust: int
wind_direction: str
precipitation: float
pressure: int
humidity: int
class GismeteoApi:
class GismeteoApi(WeatherApi):
BASE_URL = "https://www.gismeteo.ru"
async def _request(self, endpoint: str) -> str:
@@ -30,18 +21,25 @@ class GismeteoApi:
async with session.request("GET", url) as response:
return await response.text()
def _parse_oneday(self, data: str) -> List[WeatherValue]:
def _parse_oneday(self, date: datetime.date, data: str) -> WeatherResponse:
result: List[Dict[str, Any]] = []
soup = BeautifulSoup(data, features="html.parser")
location = LOCATION_PARSER.parse_location(data)
widget = ONE_DAY_PARSER.parse_widget(soup)
for parser in ROW_PARSERS:
for index, value in enumerate(parser.parse_row(widget)):
while len(result) < index + 1:
result.append({})
result[index][parser.KEY] = value
return [WeatherValue(**item) for item in result]
values = [WeatherValue(**item) for item in result]
return WeatherResponse(
location=location or "n/a",
date=date,
period="day",
values=values,
)
async def get_day(self, location_id: str, date: datetime.date) -> List[WeatherValue]:
async def get_day(self, location_id: str, date: datetime.date) -> WeatherResponse:
location = LOCATION_BUNDLE.parse(location_id)
data = await self._request(f"weather-{location}/{dateutil.dump(date)}")
return self._parse_oneday(data)
data = await self._request(f"weather-{location}/{datehelp.dump(date)}")
return self._parse_oneday(date, data)