GPTで
OpenWeather API を使い現在地の今日の天気を取得。
一時間以内に雨が降るならアラートを表示するpythonコード
としたとき
import requests
import json
# OpenWeather API キーと緯度経度を設定
api_key = 'YOUR_API_KEY'
latitude = 'YOUR_LATITUDE'
longitude = 'YOUR_LONGITUDE'
# OpenWeather One Call API の URL
url = f"https://api.openweathermap.org/data/2.5/onecall?lat={latitude}&lon={longitude}&exclude=minutely,daily&appid={api_key}&units=metric"
def get_weather_data(url):
response = requests.get(url)
return response.json()
def check_for_rain(weather_data):
hourly_forecast = weather_data.get('hourly', [])[:1] # 次の1時間の予報だけをチェック
for hour in hourly_forecast:
for weather in hour['weather']:
if weather['main'] == 'Rain':
return True
return False
# API から天気データを取得
weather_data = get_weather_data(url)
# 雨が予報されているかどうかをチェック
if check_for_rain(weather_data):
print("Alert: Rain is expected within the next hour!")
else:
print("No rain expected in the next hour.")
from geopy.geocoders import Nominatim
import geopy
def get_location():
# ジオロケーターを初期化
geolocator = Nominatim(user_agent="geoapiExercises")
try:
# 住所から位置情報を取得
location = geolocator.geocode("日本、〒郵便番号 住所", timeout=10)
# 緯度と経度を取得
if location:
latitude = location.latitude
longitude = location.longitude
return (latitude, longitude)
else:
return "Location not found", None
except geopy.exc.GeocoderTimedOut:
return "Geocoder service timed out", None
except Exception as e:
return str(e), None
# 現在地の緯度経度を取得
current_location = get_location()
if isinstance(current_location, tuple) and None not in current_location:
print("Latitude:", current_location[0])
print("Longitude:", current_location[1])
else:
print(current_location[0]) # エラーメッセージを出力
としたが変わらない
このため
現在地の緯度と経度を取得するには、Pythonで geopy ライブラリを使用するのが一般的です。geopy を使って、デバイスの IP アドレスを基にして位置情報を推測する方法
を試す
pip install geopy requests
でライブラリインポート
from geopy.geocoders import Nominatim
import requests
def get_public_ip():
# 公開 API を使用して公衆 IP アドレスを取得
response = requests.get('https://api.ipify.org')
return response.text
def get_location_by_ip(ip_address):
# IP アドレスから位置情報を推定
url = f'https://ipinfo.io/{ip_address}/json'
response = requests.get(url)
data = response.json()
loc = data.get('loc', None)
if loc:
latitude, longitude = loc.split(',')
return latitude, longitude
return None, None
# 公衆 IP アドレスを取得
public_ip = get_public_ip()
# IP アドレスから位置情報を取得
latitude, longitude = get_location_by_ip(public_ip)
print(f"Latitude: {latitude}, Longitude: {longitude}")
これなら成功
なのでこれをモジュールにして呼び出すようにする
location_utils.py
として
# location_utils.py
from geopy.geocoders import Nominatim
import requests
def get_public_ip():
"""公開 API を使用して公衆 IP アドレスを取得する関数"""
response = requests.get('https://api.ipify.org')
return response.text
def get_location_by_ip(ip_address):
"""IP アドレスから位置情報(緯度と経度)を推定する関数"""
url = f'https://ipinfo.io/{ip_address}/json'
response = requests.get(url)
data = response.json()
loc = data.get('loc', None)
if loc:
latitude, longitude = loc.split(',')
return latitude, longitude
return None, None
で保存
次に

import requests
import json
# OpenWeather API キーと緯度経度を設定
api_key = 'YOUR_API_KEY'
latitude = 'YOUR_LATITUDE'
longitude = 'YOUR_LONGITUDE'
# OpenWeather One Call API の URL
url = f"https://api.openweathermap.org/data/2.5/onecall?lat={latitude}&lon={longitude}&exclude=minutely,daily&appid={api_key}&units=metric"
def get_weather_data(url):
response = requests.get(url)
return response.json()
def check_for_rain(weather_data):
hourly_forecast = weather_data.get('hourly', [])[:1] # 次の1時間の予報だけをチェック
for hour in hourly_forecast:
for weather in hour['weather']:
if weather['main'] == 'Rain':
return True
return False
# API から天気データを取得
weather_data = get_weather_data(url)
# 雨が予報されているかどうかをチェック
if check_for_rain(weather_data):
print("Alert: Rain is expected within the next hour!")
else:
print("No rain expected in the next hour.")
の中で
location_utils.py
を呼び出して緯度経度を自動取得できるようにしたい
location_utils.py モジュールから緯度と経度を取得する機能を weather_check.py に組み込むために、以下のようにコードを修正します。まず、location_utils.py が緯度と経度を直接返すようにし、その後、この情報を weather_check.py で利用して OpenWeather API に問い合わせます。
# weather_check.py
import requests
import location_utils
# OpenWeather API キー
api_key = 'APIキー'
# 緯度と経度を location_utils から取得
latitude, longitude = location_utils.get_current_location()
if latitude is None or longitude is None:
print("Failed to get location.")
exit()
# OpenWeather One Call API の URL
url = f"https://api.openweathermap.org/data/2.5/onecall?lat={latitude}&lon={longitude}&exclude=minutely,daily&appid={api_key}&units=metric"
def get_weather_data(url):
response = requests.get(url)
return response.json()
def check_for_rain(weather_data):
hourly_forecast = weather_data.get('hourly', [])[:1]
for hour in hourly_forecast:
for weather in hour['weather']:
if weather['main'] == 'Rain':
return True
return False
# API から天気データを取得
weather_data = get_weather_data(url)
# 雨が予報されているかどうかをチェック
if check_for_rain(weather_data):
print("Alert: Rain is expected within the next hour!")
else:
print("No rain expected in the next hour.")
import location_utils2
latitude, longitude, address = location_utils2.get_current_location_and_address()
if latitude and longitude:
print(f"Latitude: {latitude}, Longitude: {longitude}")
if address:
print("Address:", address)
から
import location_utils2
latitude, longitude, address = location_utils2.get_current_location_and_address()
if latitude and longitude:
print(f"Latitude: {latitude}, Longitude: {longitude}")
if address:
print("Address:", address)
# weather_check.py
import requests
import location_utils
# OpenWeather API キー
api_key = 'APIキー'
# 緯度と経度を location_utils から取得
latitude, longitude = location_utils.get_current_location()
if latitude is None or longitude is None:
print("Failed to get location.")
exit()
# OpenWeather One Call API の URL
url = f"https://api.openweathermap.org/data/2.5/onecall?lat={latitude}&lon={longitude}&exclude=minutely,daily&appid={api_key}&units=metric"
def get_weather_data(url):
response = requests.get(url)
return response.json()
def check_for_rain(weather_data):
hourly_forecast = weather_data.get('hourly', [])[:1]
for hour in hourly_forecast:
for weather in hour['weather']:
if weather['main'] == 'Rain':
return True
return False
# API から天気データを取得
weather_data = get_weather_data(url)
# 雨が予報されているかどうかをチェック
if check_for_rain(weather_data):
print("Alert: Rain is expected within the next hour!")
else:
print("No rain expected in the next hour.")
のコードを
これを使って緯度経度取得したものへ変更
# weather_check.py
import location_utils2
import requests
def get_weather_data(api_key, latitude, longitude):
# OpenWeather One Call API の URL
url = f"https://api.openweathermap.org/data/2.5/onecall?lat={latitude}&lon={longitude}&exclude=minutely,daily&appid={api_key}&units=metric"
response = requests.get(url)
return response.json()
def check_for_rain(weather_data):
hourly_forecast = weather_data.get('hourly', [])[:1] # 次の1時間の予報だけをチェック
for hour in hourly_forecast:
for weather in hour['weather']:
if weather['main'] == 'Rain':
return True
return False
# APIキーを設定
api_key = 'APIキー'
# location_utils2から緯度と経度を取得
latitude, longitude, _ = location_utils2.get_current_location_and_address()
# 天気データを取得
weather_data = get_weather_data(api_key, latitude, longitude)
# 雨が予報されているかどうかをチェック
if check_for_rain(weather_data):
print("Alert: Rain is expected within the next hour!")
else:
print("No rain expected in the next hour.")
これを実行すれば雨が降らないので
No rain expected in the next hour.
となる
次に6時間毎の天気を表示する
weather_forecast_6hour.py
で
import requests
def get_weather_forecast(api_key, latitude, longitude):
url = f"https://api.openweathermap.org/data/2.5/onecall?lat={latitude}&lon={longitude}&units=metric&lang=ja&appid={api_key}"
response = requests.get(url)
return response.json()
# api_key = 'YOUR_API_KEY' # APIキーを設定
api_key = 'APIキー'
latitude = 35.681236 # 東京駅の緯度
longitude = 139.767125 # 東京駅の経度
weather_data = get_weather_forecast(api_key, latitude, longitude)
# 現在の天気、1時間毎の天気(次の6時間)、1日毎の天気(次の7日間)を表示
print("Current Weather:", weather_data['current'])
print("Hourly Forecast for next 6 hours:")
for hour in weather_data['hourly'][:6]:
print(hour)
print("Daily Forecast for next 7 days:")
for day in weather_data['daily'][:7]:
print(day)
としたが
Traceback (most recent call last):
File "/Users/snowpool/aw10s/rain_alert/weather_forecast_6hour.py", line 17, in <module>
print("Current Weather:", weather_data['current'])
KeyError: 'current'
{lat}&lon={lon}&exclude={part}&appid={API key}
となっていて
optional By using this parameter you can exclude some parts of the weather data from the API response. It should be a comma-delimited list (without spaces).
Available values:
• current
• minutely
• hourly
• daily
• alerts
コメント