-
Notifications
You must be signed in to change notification settings - Fork 3
/
weather_fetcher.py
41 lines (34 loc) · 1.47 KB
/
weather_fetcher.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
import json
import os
import requests
from dotenv import load_dotenv
# 위도 경도를 찾는 함수
def get_coords(province, city_district):
file_path = os.path.join(
os.path.dirname(__file__), "static", "json", "regions_coordinates.json"
)
with open(file_path, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
search_name = f"{province} {city_district}"
for item in data:
if item["name"] == search_name:
return item["lat"], item["lon"]
raise ValueError(f"{province} {city_district}에 대한 위도 경도를 찾을 수 없음")
# 날씨 정보를 가져오는 함수
def get_weather(lat, lon):
load_dotenv() # 환경 변수 로드
openweather_api_key = os.getenv('OPENWEATHER_API_KEY')
url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={openweather_api_key}"
response = requests.get(url)
return response.json()
# 지역명을 받아 날씨 정보를 반환하는 함수
def get_current_local_weather(province, city_district):
lat, lon = get_coords(province, city_district)
weather_data = get_weather(lat, lon)
return {
"temp": weather_data.get("main", {}).get("temp"),
"feels_like": weather_data.get("main", {}).get("feels_like"),
"rain_1h": weather_data.get("rain", {}).get("1h", 0),
"snow_1h": weather_data.get("snow", {}).get("1h", 0),
"main_weather": weather_data.get("weather", [{}])[0].get("main"),
}