-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.py
More file actions
38 lines (31 loc) · 1.22 KB
/
service.py
File metadata and controls
38 lines (31 loc) · 1.22 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
import requests
class WeatherService:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.openweathermap.org/data/3.0/onecall"
def fetch_current_weather(self, lat: float, lon: float) -> dict:
params = {
"lat": lat,
"lon": lon,
"appid": self.api_key,
"units": "metric",
"exclude": "minutely,hourly,daily,alerts"
}
try:
response = requests.get(self.base_url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
return {
"lat": data["lat"],
"lon": data["lon"],
"timezone": data["timezone"],
"temp": data["current"]["temp"],
"humidity": data["current"]["humidity"],
"weather": data["current"]["weather"][0]["description"]
}
except requests.exceptions.RequestException as e:
print(f"API Communication Error: {e}")
return None
except KeyError as e:
print(f"API Data Parsing Error: Missing key {e}")
return None