77# Load environment variables from .env file
88load_dotenv ()
99
10- # Load API key from environment variable (security fix)
10+ # Load API key from environment variable
1111API_KEY = os .getenv ('OPEN_WEATHER_MAP_API_KEY' )
1212
1313if not API_KEY :
1616UNIT = 'metric'
1717BASE_URL = 'https://api.openweathermap.org/data/2.5/find'
1818
19+ # Load additional environment variables
20+ CITY = os .getenv ('CITY' , 'London' ) # Default to 'London' if not provided
21+ TEMP_THRESHOLD = float (os .getenv ('TEMP_THRESHOLD' , 30.0 )) # Default to 30°C
22+ WIND_SPEED_THRESHOLD = float (os .getenv ('WIND_SPEED_THRESHOLD' , 10.0 )) # Default to 10 m/s
1923
20- def fetch_weather (city ):
21- """Fetches weather data for a given city.
22-
23- Args:
24- city (str): Name of the city.
25-
26- Returns:
27- dict: Weather data if successful, None otherwise.
28- """
2924
25+ def fetch_weather (city ):
26+ """Fetches weather data for a given city."""
3027 url = f"{ BASE_URL } ?q={ city } &appid={ API_KEY } &units={ UNIT } "
3128 response = requests .get (url )
32-
3329 if response .status_code == 200 :
3430 return response .json ()
3531 else :
@@ -38,16 +34,7 @@ def fetch_weather(city):
3834
3935
4036def check_alerts (data , temp_threshold , wind_speed_threshold ):
41- """Checks for temperature and wind speed alerts in weather data.
42-
43- Args:
44- data (dict): Weather data.
45- temp_threshold (float): Temperature threshold in °C.
46- wind_speed_threshold (float): Wind speed threshold in m/s.
47-
48- Prints alerts if any, otherwise prints a message indicating normal weather conditions.
49- """
50-
37+ """Checks for temperature and wind speed alerts in weather data."""
5138 if not data or 'list' not in data or not data ['list' ]:
5239 print ("No data available to check alerts." )
5340 return
@@ -69,20 +56,14 @@ def check_alerts(data, temp_threshold, wind_speed_threshold):
6956
7057
7158def main ():
72- """Prompts user for city name, temperature and wind speed thresholds,
73- and continuously checks for alerts.
74- """
75-
76- city = input ("Enter city name: " )
77- temp_threshold = float (input ("Enter temperature threshold (°C): " ))
78- wind_speed_threshold = float (input ("Enter wind speed threshold (m/s): " ))
79-
59+ """Continuously checks for weather alerts based on environment variables."""
8060 while True :
81- weather_data = fetch_weather (city )
82- check_alerts (weather_data , temp_threshold , wind_speed_threshold )
61+ weather_data = fetch_weather (CITY )
62+ check_alerts (weather_data , TEMP_THRESHOLD , WIND_SPEED_THRESHOLD )
8363 print ("Waiting for the next check..." )
8464 time .sleep (3600 ) # check every hour
8565
8666
8767if __name__ == "__main__" :
88- main ()
68+ main ()
69+
0 commit comments