11import requests
22import json
33import time
4+ import os
5+ from dotenv import load_dotenv
6+
7+ # Load environment variables from .env file
8+ load_dotenv ()
9+
10+ # Load API key from environment variable (security fix)
11+ API_KEY = os .getenv ('OPEN_WEATHER_MAP_API_KEY' )
12+
13+ if not API_KEY :
14+ raise ValueError ("Missing environment variable 'OPEN_WEATHER_MAP_API_KEY'" )
415
5- API_KEY = '7e3f21edee540e6110af347b55eb1ab2'
616UNIT = 'metric'
717BASE_URL = 'https://api.openweathermap.org/data/2.5/find'
818
19+
920def fetch_weather (city ):
10- try :
11- url = f"{ BASE_URL } ?q={ city } &appid={ API_KEY } &units={ UNIT } "
12- response = requests .get (url )
13- if response .status_code == 200 :
14- return response .json ()
15- else :
16- print (f"Error fetching data: { response .status_code } " )
17- return None
18- except Exception as e :
19- print (f"An error occurred: { e } " )
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+ """
29+
30+ url = f"{ BASE_URL } ?q={ city } &appid={ API_KEY } &units={ UNIT } "
31+ response = requests .get (url )
32+
33+ if response .status_code == 200 :
34+ return response .json ()
35+ else :
36+ print (f"Error fetching data: { response .status_code } " )
2037 return None
2138
39+
2240def 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+
2351 if not data or 'list' not in data or not data ['list' ]:
2452 print ("No data available to check alerts." )
2553 return
@@ -39,7 +67,12 @@ def check_alerts(data, temp_threshold, wind_speed_threshold):
3967 else :
4068 print ("No alerts. Weather conditions are normal." )
4169
70+
4271def main ():
72+ """Prompts user for city name, temperature and wind speed thresholds,
73+ and continuously checks for alerts.
74+ """
75+
4376 city = input ("Enter city name: " )
4477 temp_threshold = float (input ("Enter temperature threshold (°C): " ))
4578 wind_speed_threshold = float (input ("Enter wind speed threshold (m/s): " ))
@@ -48,7 +81,8 @@ def main():
4881 weather_data = fetch_weather (city )
4982 check_alerts (weather_data , temp_threshold , wind_speed_threshold )
5083 print ("Waiting for the next check..." )
51- # check every hour
52- time .sleep (3600 )
84+ time .sleep (3600 ) # check every hour
85+
86+
5387if __name__ == "__main__" :
54- main ()
88+ main ()
0 commit comments