forked from Abdullish/weather-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather_dashboard.py
108 lines (92 loc) · 3.72 KB
/
weather_dashboard.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import os
import json
import boto3
import requests
from datetime import datetime
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
class WeatherDashboard:
def __init__(self):
# Load API keys and bucket name from environment variables
self.api_key = os.getenv("OPENWEATHER_API_KEY")
self.bucket_name = os.getenv("AWS_BUCKET_NAME")
self.s3_client = boto3.client("s3")
# Validate the environment variables
if not self.api_key:
raise ValueError("OPENWEATHER_API_KEY is not set in environment variables")
if not self.bucket_name:
raise ValueError("AWS_BUCKET_NAME is not set in environment variables")
def create_bucket_if_not_exists(self):
"""Create S3 bucket if it doesn't exist"""
try:
self.s3_client.head_bucket(Bucket=self.bucket_name)
print(f"Bucket '{self.bucket_name}' already exists.")
except:
print(f"Creating bucket '{self.bucket_name}'...")
try:
# Create bucket (us-east-1 region does not require location constraint)
self.s3_client.create_bucket(Bucket=self.bucket_name)
print(f"Successfully created bucket '{self.bucket_name}'.")
except Exception as e:
print(f"Error creating bucket: {e}")
def fetch_weather(self, city):
"""Fetch weather data from OpenWeather API"""
base_url = "http://api.openweathermap.org/data/2.5/weather"
params = {
"q": city,
"appid": self.api_key,
"units": "imperial"
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching weather data: {e}")
return None
def save_to_s3(self, weather_data, city):
"""Save weather data to S3 bucket"""
if not weather_data:
return False
timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
file_name = f"weather-data/{city}-{timestamp}.json"
try:
weather_data["timestamp"] = timestamp
self.s3_client.put_object(
Bucket=self.bucket_name,
Key=file_name,
Body=json.dumps(weather_data),
ContentType="application/json"
)
print(f"Successfully saved weather data for '{city}' to S3.")
return True
except Exception as e:
print(f"Error saving to S3: {e}")
return False
def main():
dashboard = WeatherDashboard()
# Create S3 bucket if it doesn't exist
dashboard.create_bucket_if_not_exists()
cities = ["Nigeria", "Abuja", "Lagos"]
for city in cities:
print(f"\nFetching weather for '{city}'...")
weather_data = dashboard.fetch_weather(city)
if weather_data:
print(f"Weather data for '{city}':")
temp = weather_data["main"]["temp"]
feels_like = weather_data["main"]["feels_like"]
humidity = weather_data["main"]["humidity"]
description = weather_data["weather"][0]["description"]
print(f" Temperature: {temp}°F")
print(f" Feels like: {feels_like}°F")
print(f" Humidity: {humidity}%")
print(f" Conditions: {description}")
# Save the data to S3
success = dashboard.save_to_s3(weather_data, city)
if success:
print(f"Weather data for '{city}' successfully saved to S3.")
else:
print(f"Failed to fetch weather data for '{city}'.")
if __name__ == "__main__":
main()