File size: 997 Bytes
cdf8921 |
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 |
import os
import requests
from dotenv import load_dotenv
class OpenWeatherClient:
def __init__(self):
load_dotenv()
self.api_key = os.getenv("OPEN_WEATHER_TOKEN")
self.base_url = "http://api.openweathermap.org/data/2.5/weather"
def get_weather(self, location: str):
params = {
"q": location,
"appid": self.api_key,
"units": "metric"
}
try:
response = requests.get(self.base_url, params=params)
response.raise_for_status()
weather_data = response.json()
condition = weather_data["weather"][0]["description"]
temp_c = weather_data["main"]["temp"]
return {
"location": location,
"condition": condition.capitalize(),
"temperature": f"{temp_c}°C"
}
except requests.exceptions.RequestException as e:
return {"error": f"Failed to fetch weather data: {e}"} |