-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather_app.py
63 lines (43 loc) · 1.94 KB
/
weather_app.py
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
import os
from dotenv import load_dotenv
import requests
from pprint import pprint
# Load environment variables
load_dotenv()
def get_current_weather(city="Cairo"):
# Retrieve API_KEY from the environment variable file
api_key = os.getenv('API_KEY')
# Check if API_KEY exists
if not api_key:
raise ValueError("API_KEY is missing. Please set it in your .env file.")
# Create the request URL using the user's input and API key from environment variables
request_url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
try:
# Retrieve and display the weather data
weather_data = requests.get(request_url).json()
# Check if the request was successful
if weather_data['cod'] != 200:
print(f"\n❌ Error: {weather_data['message']}")
return weather_data
except requests.RequestException as error:
print(f"Network error: {error}")
return None
except ValueError as e:
print(f"Error: {e}")
return None
if __name__ == '__main__':
print("\n======= Welcome To The Weather-Conditions Page =======\n")
# Ask user to enter a city name.
city_name = input("Please, enter a city name: ")
weather_data = get_current_weather(city_name)
if weather_data is not None:
# Display more readable data for users.
print(f"\nCurrent Weather for '{city_name.title()}' City - {weather_data['sys']['country']}:")
print(f"Temperature : {weather_data['main']['temp']}°C")
print(f"Feels like : {weather_data['main']['feels_like']}°C")
print(f"Weather : {weather_data['weather'][0]['description'].capitalize()}")
"""
Refactored the weather request logic:
- Allowing it to be reused as a module for the Flask web application,
- Enabling separation of concerns between data retrieval and the web interface.
"""