-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.py
43 lines (34 loc) · 1.32 KB
/
weather.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
import requests
from dotenv import load_dotenv
import os
from dataclasses import dataclass
load_dotenv()
api_key = os.getenv('API_KEY')
@dataclass
class WeatherData:
main: str
description: str
icon: str
temperature: int
def get_lat_lon(city_name, state_code, country_code, API_key):
resp = requests.get(f'http://api.openweathermap.org/geo/1.0/direct?q={city_name},{state_code},{country_code}&appid={API_key}').json()
data= resp[0]
lat, lon = data.get('lat'), data.get('lon')
return lat, lon
def get_current_weather(lat, lon, API_key):
resp = requests.get(f'https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API_key}&units=imperial').json()
data = WeatherData(
main=resp.get('weather')[0].get('main'),
description=resp.get('weather')[0].get('description'),
icon=resp.get('weather')[0].get('icon'),
temperature=int(resp.get('main').get('temp')),
)
print(data.temperature)
return data
def main(city_name, state_name, country_name):
lat, lon = get_lat_lon(city_name, state_name, country_name, api_key)
weather_data = get_current_weather(lat, lon, api_key)
return weather_data
if __name__=="__main__":
lat, lon = get_lat_lon('Thousand Oaks', 'CA', 'United States', api_key)
print(get_current_weather(lat, lon, api_key))