open meteo apisi ile hava durumunu ve rüzgar şiddetini gösteren python kodu

import requests
import json
def get_weather_data(city_name):
"""
Open-Meteo API'sinden şehir adına göre sıcaklık ve rüzgar verilerini çeker.
Öncelikle Nominatim API ile şehir adını enlem ve boylama dönüştürür.
Sadece gerçek yerleşim yerleri (şehir, kasaba, köy) için bilgi gösterir.
"""
headers = {
'User-Agent': 'HavaDurumuUygulamam/1.0 (your_email@example.com)' # Kendi e-posta adresinizi girin
}
# 1. Adım: Şehir adını enlem ve boylama dönüştürme
geocoding_url = f"https://nominatim.openstreetmap.org/search?q={city_name}&format=json&limit=1"
try:
geocoding_response_obj = requests.get(geocoding_url, headers=headers, timeout=10)
geocoding_response_obj.raise_for_status()
try:
geocoding_response = geocoding_response_obj.json()
except json.decoder.JSONDecodeError as e:
print(f"\nDEBUG: Nominatim API'den geçersiz JSON yanıtı alındı. İlk 500 karakter:\n{geocoding_response_obj.text[:500]}...")
return f"Konum bilgisi alınırken hata: API yanıtı geçerli bir JSON değil ({e})."
if not geocoding_response:
return f"'{city_name}' için konum bilgisi bulunamadı. Lütfen şehir adını kontrol edin."
first_result = geocoding_response[0]
result_class = first_result.get('class')
result_type = first_result.get('type')
display_name = first_result.get('display_name', city_name)
valid_place_types = ['city', 'town', 'village', 'hamlet', 'borough', 'suburb', 'county']
# Yeni: Daha esnek yer kontrolü
if result_class != 'place' or result_type not in valid_place_types:
if 'lat' in first_result and 'lon' in first_result:
print(f"\nUYARI: '{city_name}' için yerleşim yeri bulunamadı ancak konum bilgisi mevcut. '{display_name}' konumundan veri çekiliyor.")
else:
return (f"'{city_name}' için geçerli bir şehir, kasaba veya köy bulunamadı. "
f"Bulunan konum bir '{result_class}/{result_type}' türünde ve '{display_name}' olarak adlandırılıyor.")
latitude = first_result['lat']
longitude = first_result['lon']
# 2. Adım: Open-Meteo API'den hava durumu verisi alma
weather_url = (f"https://api.open-meteo.com/v1/forecast?"
f"latitude={latitude}&longitude={longitude}&"
f"current=temperature_2m,wind_speed_10m&forecast_days=1&wind_speed_unit=ms")
weather_response_obj = requests.get(weather_url, headers=headers, timeout=10)
weather_response_obj.raise_for_status()
try:
weather_response = weather_response_obj.json()
except json.decoder.JSONDecodeError as e:
print(f"\nDEBUG: Open-Meteo API'den geçersiz JSON yanıtı alındı. İçerik:\n{weather_response_obj.text[:500]}...")
return f"Hava durumu bilgisi alınırken hata: API yanıtı geçerli bir JSON değil ({e})."
if "current" in weather_response:
temperature = weather_response['current']['temperature_2m']
wind_speed_ms = weather_response['current']['wind_speed_10m']
wind_speed_kmh = round(wind_speed_ms * 3.6, 2)
return (f"--- {display_name} için Güncel Hava Durumu ---\n"
f"Sıcaklık: {temperature}°C\n"
f"Rüzgar hızı: {wind_speed_ms} m/s ({wind_speed_kmh} km/h)")
else:
print(f"\nDEBUG: Open-Meteo API yanıtında 'current' anahtarı bulunamadı. Tam yanıt:\n{json.dumps(weather_response, indent=2)}")
return f"'{display_name}' için hava durumu bilgileri alınamadı. API yanıtında 'current' verisi eksik."
except requests.exceptions.HTTPError as e:
error_message = f"HTTP hatası oluştu ({e.response.status_code}): {e.response.reason}."
print(f"\nDEBUG: HTTP Hata URL: {e.request.url}, Yanıt İçeriği (İlk 500 karakter):\n{e.response.text[:500]}...")
if e.response.status_code == 400:
error_message += " İstek parametrelerinde bir sorun olabilir."
elif e.response.status_code == 403:
error_message += " Erişim engellendi. Nominatim kullanım politikasını ihlal etmiş olabilirsiniz."
elif e.response.status_code == 404:
error_message += " İstenen kaynak bulunamadı."
elif e.response.status_code >= 500:
error_message += " API sunucusunda geçici bir sorun olabilir."
return error_message + " Lütfen daha sonra tekrar deneyin."
except requests.exceptions.ConnectionError:
return "İnternet bağlantısı hatası. Lütfen bağlantınızı kontrol edin."
except requests.exceptions.Timeout:
return "İstek zaman aşımına uğradı. Ağ bağlantınızda bir sorun olabilir veya API'ler meşgul olabilir."
except requests.exceptions.RequestException as e:
print(f"\nDEBUG: Genel ağ hatası: {e}")
return f"Genel bir ağ hatası oluştu: {e}. Lütfen bağlantınızı kontrol edin."
except Exception as e:
print(f"\nDEBUG: Beklenmeyen hata: {e}")
return f"Beklenmeyen bir hata oluştu: {e}. Lütfen geliştiriciye bildirin."
def main():
print("Hava durumu bilgilerini almak için şehir adı girin. Çıkmak için 'q' tuşuna basın.")
while True:
city_input = input("\nŞehir adı: ").strip()
if city_input.lower() == 'q':
print("Programdan çıkılıyor. Hoşça kalın!")
break
if not city_input:
print("Lütfen geçerli bir şehir adı girin.")
continue
result = get_weather_data(city_input)
print(result)
if __name__ == "__main__":
main()