timezone fix

This commit is contained in:
2026-04-02 09:53:14 +03:00
parent e8544ebb38
commit 684a952158
3 changed files with 67 additions and 30 deletions

View File

@@ -1,5 +1,7 @@
import aiohttp
from datetime import datetime
import asyncio
import logging
async def get_coords_by_city(city_name: str):
"""Ищет координаты по названию города."""
@@ -9,18 +11,31 @@ async def get_coords_by_city(city_name: str):
try:
async with session.get(url, timeout=5) as response:
if response.status != 200:
return None, None, None
return None, None, None, None
data = await response.json()
results = data.get("results")
if not results:
return None, None, None
return None, None, None, None
city_data = results[0]
return city_data.get("latitude"), city_data.get("longitude"), city_data.get("name", city_name)
return (
city_data.get("latitude"),
city_data.get("longitude"),
city_data.get("name", city_name),
city_data.get("timezone")
)
except Exception:
return None, None, None
return None, None, None, None
async def get_timezone_by_coords(lat: float, lon: float) -> str | None:
"""Определяет часовой пояс по координатам, делая запрос к API погоды."""
# Делаем минимальный запрос к API, чтобы получить часовой пояс
data = await fetch_weather_data(lat, lon, 1)
if data and "timezone" in data:
return data["timezone"]
return None
async def fetch_weather_data(lat: float, lon: float, days: int):
"""Базовая функция для запроса данных о погоде на N дней."""
@@ -30,14 +45,20 @@ async def fetch_weather_data(lat: float, lon: float, days: int):
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_max"
f"&timezone=auto&forecast_days={days}"
)
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, timeout=5) as response:
if response.status != 200:
return None
return await response.json()
except Exception:
return None
# Логика с повторными попытками для надежности
for attempt in range(3):
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, timeout=10) as response:
if response.status == 200:
return await response.json()
logging.warning(f"Попытка {attempt+1}: API погоды вернуло статус {response.status}")
except Exception as e:
logging.warning(f"Попытка {attempt+1}: Ошибка при запросе к API погоды: {e}")
if attempt < 2: # Не спим после последней попытки
await asyncio.sleep(attempt + 2) # Спим 2, 3 секунды
return None
async def get_daily_weather_summary(lat: float, lon: float) -> str:
"""Прогноз на сегодня."""