padel/padel/weather.py

41 lines
1.0 KiB
Python
Raw Permalink Normal View History

2021-08-11 13:55:39 +02:00
import requests
2021-08-11 16:28:28 +02:00
from datetime import datetime
2021-08-11 13:55:39 +02:00
class WeatherAPI:
BASE_URL = "https://api.weatherapi.com/v1"
def __init__(self, api_key):
self._api_key = api_key
def _get(self, endpoint, params):
params["key"] = self._api_key
return requests.get(f"{self.BASE_URL}{endpoint}", params=params)
2021-08-11 15:48:03 +02:00
async def get_hourly_conditions(self, query, days=1):
2021-08-11 16:42:34 +02:00
r = self._get(
"/forecast.json",
{
"q": query,
"days": days,
"aqi": "no",
"alert": "no",
},
)
2021-08-11 13:55:39 +02:00
if r.status_code != 200:
return None
data = r.json()
2021-08-11 16:42:34 +02:00
hour_forecasts = sum(
[obj["hour"] for obj in data["forecast"]["forecastday"]], []
)
2021-08-11 16:28:28 +02:00
return [
(
datetime.fromtimestamp(forecast["time_epoch"]),
forecast["condition"]["text"],
forecast["condition"]["code"],
2021-08-11 16:42:34 +02:00
)
for forecast in hour_forecasts
2021-08-11 16:28:28 +02:00
]