티스토리 뷰

반응형

0. 들어가면서

앞에서 우리는 ip값을 이용해서 경도와 위도를 알아보았다. 이제는 알게된 경도와 위도를 이용하여 날씨를 알아보자.

 

빠르게 날씨 예측을 하고 싶다면, 인증키 받고 바로 가장 아래로 스크롤을 내리자.

 

1. Openweathermap 인증키 받기

openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

2 Billion Forecasts Per Day 2,500 new subscribers a day 2,600,000 customers 20+ weather APIs 2 Billion Forecasts Per Day 2,500 new subscribers a day 2,600,000 customers 20+ weather APIs

openweathermap.org

일단 홈페이지에 접속하여 회원가입을 한 후에 로그인을 하자.

오른쪽 위를 보면 My API Keys를 눌러보면 발급된 키를 확인할 수 있다.

 

 

 

 

2. pyowm

이제 라이브러리를 다운 받자. github 주소는 아래를 참고하자.

github.com/csparpa/pyowm/

 

csparpa/pyowm

A Python wrapper around the OpenWeatherMap web API - csparpa/pyowm

github.com

 

documentation은 아래를 참고하자.

pyowm.readthedocs.io/en/latest/

 

PyOWM — pyowm documentation

PyOWM Welcome to PyOWM v3 documentation! What is PyOWM? PyOWM is a client Python wrapper library for OpenWeatherMap web APIs. It allows quick and easy consumption of OWM data from Python applications via a simple object model and in a human-friendly fashio

pyowm.readthedocs.io

 

사실 위에는 복잡하고 참고할 만한 홈페이지는 아래와 같다.

openweathermap.org/api/one-call-api

 

One Call API: weather data for any geographical coordinate - OpenWeatherMap

To learn about how get access to historical weather data for the previous 5 days, please use this section of the documentation. How to make an API call https://api.openweathermap.org/data/2.5/onecall/timemachine?lat={lat}&lon={lon}&dt={time}&appid={API key

openweathermap.org

 

 

3. 구현

> pip install pyowm

으로 일단 설치부터 하자.

 

코드를 칠 예정이다. 순차적으로 따라 치면 된다.

 

 

 

3.1 Import the pyOWM library

form pyowm import OWM

 

 

3.2 Create global OWM object

회원가입을 하고 받은 API_key가 있을 것이다. 담아주자. 아래 처럼 간단하게 담아주는 것을 알 수 있다.

 

API_key = '받은 키 넣자'
owm = OWM(API_key)

 

 

3.3 Getting currently observed weather for a specific location

현재 날씨를 알기 위해 위치와 OWM을 함꼐 제공하는 방법은 세가지가 있다. 장소 이름을 적어도되고, City ID를 적어도 뒨다. 그리고 lat/lon(경도위도를 적어줘도 된다.) 아래의 세가지 중 한기지만 써주면된다.

 

obs = owm.weather_at_place('London,GB')               # Toponym
obs = owm.weather_at_id(2643741)                      # city ID
obs = owm.weather_at_coords(-0.107331,51.503614)      # lat/lon

 

여기서 입력한 지역과 지역에 매칭되는 날씨 정보를 포함한 observation 객체가 리턴된다. 즉, 여기서 핵심은 날씨와 관련된 데이터를 포함한 Weather 객체와 지역에 대한 데이터를 가진 Location 객체이다.

 

 

 

3.4 원하는 정보 불러오기

# Weather 객체
seoul_weather = obs.get_weather()
print(seoul_weather)   # <Weather - reference time=2013-12-18 09:20, status=Clouds> 를 출력한다.


# Location 객체
location_seoul = observation.get_location()
print(location_seoul)

 

3.4.1 weather 객체로 날씨 불러오기

 

seoul_weather.get_wind()                  # {'speed': 4.6, 'deg': 330}
seoul_weather.get_humidity()              # 87
seoul_weather.get_rain()                  # Get rain volume
seoul_weather.get_clouds()                # Get cloud coverage 
seoul_weather.get_snow()                  # Get snow volume
seoul_weather.get_wind()                  # Get wind degree and speed
seoul_weather.get_pressure()              # 기압

seoul_weather.get_temperature()           # 온도(캘빈온도)
seoul_weather.get_temperature('celsius')  # {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0}

seoul_weather.get_status()                # Get weather short status ex) 'Clouds'
seoul_weather.get_detailed_status()       # ex) 'Broken clouds'
seoul_weather.get_weather_code()          # owm에서 사용하는 상태코드 - ex) 803
seoul_weather.get_sunrise_time()          # 일출시각 ex) 1377862896L
seoul_weather.get_sunset_time('iso')      # 일몰시각(iso시간) ex) '2013-08-30 20:07:57+00'

 

3.4.2 Location 객체로 속성 보기

 

location_seoul.get_name()    # 'Seoul'
location_seoul.get_lon()     # 경도
location_seoul.get_lat()     # 위도
location_seoul.get_ID()      # 도시ID

 

 

우리가 라이브러리를 쓰는 이유는 방대한 양의 정보를 알아 낼 수 있다는 것이다.

 

 

4. ERROR 시

EEROR로 적어보겠다.

 

from pyowm import OWM

API_key = '____________'
owm = OWM(API_key)
obs = owm.weather_at_coords(-0.107331,51.503614)  
seoul_weather = obs.get_weather()
print(seoul_weather)
res = seoul_weather.get_wind() 
print(res)

 

 대략 이렇게 해서 돌려봤는데...

AttributeError: 'OWM' object has no attribute 'weather_at_coords'

에러가 뜬다... 찾아보니 pyowm 3버전부터는 바로 호출이 안되고...

mgr = owm.weather_manager()을 추가해야 된다. 그래서 추가했다.

 

from pyowm import OWM

API_key = '_____________________'
owm = OWM(API_key)
mgr = owm.weather_manager()
obs = mgr.weather_at_coords(-0.107331,51.503614)  
seoul_weather = obs.get_weather()
print(seoul_weather)
res = seoul_weather.get_wind() 
print(res)

 

그러니 다음 에러가 날 반긴다..

AttributeError: 'Observation' object has no attribute 'get_weather'

찾다보니 싸하다............. 버전 바뀌면서 다 바뀐듯??


결국 공식문서 찾아서 아래와 같이 구현을 하긴했다.... 완전 바뀐듯하다..

 

from pyowm import OWM

API_key = '_______________________'
owm = OWM(API_key)
mgr = owm.weather_manager()
obs = mgr.weather_at_place('London,GB')      
w = obs.weather
print(w)
res = w.status 
print(res) # Rain
res1 = w.detailed_status
print(res1) # moderate/light rain

w2 = obs.weather.wind()
print(w2)            # {'speed': 4.39, 'deg': 42}

 

 

 


정말 단순하게 온도를 알고 싶다면 다음과 같이 하면된다.

 

import requests
lat = 경도를 적어주세요
lng = 위도를 적어주세요

weather_url = f'https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lng}&exclude=hourly,daily&appid=____나의인증키를넣어준다____'
res = requests.get(weather_url)
data = res.json()
temp = data['current']['temp']-273.15
if temp < 0:
    print(f'현재 온도는 {temp}도 입니다. 목도리하고 나가세요!')

 

관련 공식문서는 아래를 참고하자.

openweathermap.org/api/one-call-api

 

One Call API: weather data for any geographical coordinate - OpenWeatherMap

To learn about how get access to historical weather data for the previous 5 days, please use this section of the documentation. How to make an API call https://api.openweathermap.org/data/2.5/onecall/timemachine?lat={lat}&lon={lon}&dt={time}&appid={API key

openweathermap.org

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함