-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
296 lines (255 loc) · 12 KB
/
Copy pathmain.py
File metadata and controls
296 lines (255 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import json
import httpx
import logging
from pydantic import BaseModel
from pydantic import validator
from contextlib import asynccontextmanager
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi import FastAPI, HTTPException, Request, Response
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
WEATHER_API_URL = "https://api.open-meteo.com/v1/forecast"
GEOCODE_API_URL = "https://nominatim.openstreetmap.org"
WEATHER_CODES = {
0: "Ясно",
1: "В основном ясно",
2: "Частично облачно",
3: "Пасмурно",
45: "Туман",
48: "Изморозь",
51: "Легкая морось",
53: "Умеренная морось",
55: "Сильная морось",
61: "Легкий дождь",
63: "Умеренный дождь",
65: "Сильный дождь",
71: "Легкий снег",
73: "Умеренный снег",
75: "Сильный снег",
80: "Ливневые дожди",
95: "Гроза"
}
http_client: httpx.AsyncClient | None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Управление жизненным циклом приложения"""
global http_client
# Startup
http_client = httpx.AsyncClient(
timeout=httpx.Timeout(10.0),
headers={"User-Agent": "Weather-App/1.0"}
)
logger.info("HTTP клиент инициализирован")
yield
# Shutdown
if http_client:
await http_client.aclose()
logger.info("HTTP клиент закрыт")
app = FastAPI(
title="Приложение погоды",
description="Простое API для получения погоды",
lifespan=lifespan
)
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
class CoordinatesRequest(BaseModel):
latitude: float
longitude: float
@validator('latitude')
def validate_latitude(cls, value):
if not (-90 <= value <= 90):
raise ValueError("Широта должна быть в диапазоне от -90 до 90")
return value
@validator('longitude')
def validate_longitude(cls, value):
if not (-180 <= value <= 180):
raise ValueError("Долгота должна быть в диапазоне от -180 до 180")
return value
class WeatherResponse(BaseModel):
latitude: float
longitude: float
city: str | None
temperature: float
humidity: int
wind_speed: float
weather_description: str
timezone: str
class CookieManager:
"""Класс для работы с cookie."""
@staticmethod
def get_recent_city(request: Request) -> dict | None:
"""Получить последний город из cookies."""
recent_city_data = request.cookies.get("recent_city")
if recent_city_data:
try:
return json.loads(recent_city_data)
except json.JSONDecodeError as e:
logging.error("Ошибка декодирования JSON из cookies recent_city: %s", e)
return None
return None
@staticmethod
def save_recent_city(response: Response, lat: float, lon: float):
"""Сохранить последний город в cookies."""
city_data = {
"latitude": lat,
"longitude": lon
}
response.set_cookie(
"recent_city",
json.dumps(city_data, ensure_ascii=False),
max_age=30*24*60*60 # 30 дней
)
class WeatherService:
"""Сервис для работы с погодой."""
@staticmethod
async def get_city_by_coords(lat: float, lon: float) -> str:
try:
geocode_url = f"{GEOCODE_API_URL}/reverse"
params = {
"lat": lat,
"lon": lon,
"format": "json"
}
if not http_client:
raise HTTPException(status_code=500, detail="HTTP клиент не инициализирован")
response = await http_client.get(geocode_url, params=params)
response.raise_for_status()
geocode_data = response.json()
address = geocode_data.get('address', {})
city_fields = ['city', 'town', 'village', 'municipality', 'county']
for field in city_fields:
if field in address:
return address[field]
display_name = geocode_data.get('display_name', '') if geocode_data else ''
if display_name:
return display_name.split(',')[0]
except httpx.HTTPError as e:
logging.error(f"Ошибка при получении города по координатам: {e}")
except (KeyError, IndexError, json.JSONDecodeError) as e:
logging.error(f"Ошибка обработки данных геокодирования: {e}")
except Exception as e:
logging.error(f"Неизвестная ошибка: {e}")
return f"Координаты {lat:.2f}, {lon:.2f}"
@staticmethod
async def get_weather_by_coords(lat: float, lon: float, city_name: str | None = None) -> WeatherResponse:
"""Получить погоду по координатам"""
try:
if not city_name:
city_name = await WeatherService.get_city_by_coords(lat, lon)
params = {
"latitude": lat,
"longitude": lon,
"current": "temperature_2m,relative_humidity_2m,wind_speed_10m,weather_code",
"timezone": "auto"
}
if not http_client:
raise HTTPException(status_code=500, detail="HTTP клиент не инициализирован")
response = await http_client.get(WEATHER_API_URL, params=params)
response.raise_for_status()
weather_data = response.json()
if not weather_data or 'current' not in weather_data:
raise HTTPException(status_code=404, detail="Погода не найдена для указанных координат")
current = weather_data['current']
return WeatherResponse(
latitude=lat,
longitude=lon,
city=city_name,
temperature=current['temperature_2m'],
humidity=int(current['relative_humidity_2m']),
wind_speed=current['wind_speed_10m'],
weather_description=WEATHER_CODES.get(current['weather_code'], "Неизвестно"),
timezone=weather_data.get('timezone', '')
)
except httpx.HTTPError as e:
logging.error(f"Ошибка при получении погоды: {e}")
raise HTTPException(status_code=500, detail="Ошибка при получении погоды")
except (KeyError, ValueError, TypeError) as e:
logging.error(f"Ошибка обработки данных погоды: {e}")
raise HTTPException(status_code=500, detail="Ошибка обработки данных погоды")
except Exception as e:
logging.error(f"Неизвестная ошибка: {e}")
raise HTTPException(status_code=500, detail=f"Ошибка при получении погоды: {str(e)}")
@staticmethod
async def get_coordinates_by_city(city: str) -> tuple[float, float, str]:
"""Получить координаты по названию города"""
try:
geocode_url = f"{GEOCODE_API_URL}/search"
params = {
"q": city,
"format": "json",
"limit": 1
}
if not http_client:
raise HTTPException(status_code=500, detail="HTTP клиент не инициализирован")
response = await http_client.get(geocode_url, params=params)
response.raise_for_status()
geocode_data = response.json()
if not geocode_data or len(geocode_data) == 0:
raise HTTPException(status_code=404, detail=f"Город '{city}' не найден")
location = geocode_data[0]
lat = float(location['lat'])
lon = float(location['lon'])
display_name = location.get('display_name', '').split(',')[0]
return lat, lon, display_name
except httpx.HTTPError as e:
logging.error(f"Ошибка при получении координат города '{city}': {e}")
raise HTTPException(status_code=500, detail="Ошибка при получении координат города")
except (KeyError, IndexError, json.JSONDecodeError) as e:
logging.error(f"Ошибка обработки данных геокодирования для города '{city}': {e}")
raise HTTPException(status_code=500, detail="Ошибка обработки данных геокодирования")
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
"""Главная страница"""
recent_city = CookieManager.get_recent_city(request)
if recent_city and 'latitude' in recent_city and 'longitude' in recent_city:
try:
city_name = await WeatherService.get_city_by_coords(
recent_city['latitude'],
recent_city['longitude']
)
recent_city['city'] = city_name
except Exception as e:
logger.warning(f"Ошибка при получении названия города: {e}")
recent_city = None
return templates.TemplateResponse("index.html", {
"request": request,
"recent_city": recent_city
})
@app.post("/weather/coordinates")
async def get_weather_by_coordinates(
request: CoordinatesRequest,
response: Response
) -> JSONResponse:
"""Получить погоду по координатам из геолокации"""
try:
weather_data = await WeatherService.get_weather_by_coords(
request.latitude,
request.longitude
)
CookieManager.save_recent_city(response, request.latitude, request.longitude)
logger.info(f"Получена погода для координат {request.latitude}, {request.longitude}")
return JSONResponse(content=weather_data.dict())
except HTTPException:
raise
except Exception as e:
logger.error(f"Неожиданная ошибка при получении погоды по координатам: {e}")
raise HTTPException(status_code=500, detail="Внутренняя ошибка сервера")
@app.get("/weather", response_model=WeatherResponse)
async def get_weather_data(city: str, response: Response) -> WeatherResponse:
"""Получить данные о погоде для города"""
if not city or not city.strip():
raise HTTPException(status_code=400, detail="Название города не может быть пустым")
city = city.strip()
try:
lat, lon, display_name = await WeatherService.get_coordinates_by_city(city)
weather_data = await WeatherService.get_weather_by_coords(lat, lon, display_name)
CookieManager.save_recent_city(response, lat, lon)
logger.info(f"Получена погода для города {city}")
return weather_data
except HTTPException:
raise
except Exception as e:
logger.error(f"Неожиданная ошибка при получении погоды для города {city}: {e}")
raise HTTPException(status_code=500, detail="Внутренняя ошибка сервера")