1+ import openmeteo_requests
2+
3+ import pandas as pd
4+ import requests_cache
5+ from retry_requests import retry
6+
7+ class ExternalAPIsCoordinator :
8+ def __init__ (self ):
9+ pass
10+
11+ def get_weather (self , latitude : float , longitude : float ):
12+ """
13+ Get weather data for a given latitude and longitude.
14+
15+ Args:
16+ latitude (float): The latitude of the location.
17+ longitude (float): The longitude of the location.
18+
19+ Returns:
20+ dict: A dictionary containing the weather data.
21+ """
22+
23+ # Setup the Open-Meteo API client with cache and retry on error
24+ cache_session = requests_cache .CachedSession ('.cache' , expire_after = 3600 )
25+ retry_session = retry (cache_session , retries = 5 , backoff_factor = 0.2 )
26+ openmeteo = openmeteo_requests .Client (session = retry_session )
27+
28+ # Make sure all required weather variables are listed here
29+ # The order of variables in hourly or daily is important to assign them correctly below
30+ url = "https://api.open-meteo.com/v1/forecast"
31+ params = {
32+ "latitude" : latitude ,
33+ "longitude" : longitude ,
34+ "hourly" : "temperature_2m" ,
35+ }
36+ responses = openmeteo .weather_api (url , params = params )
37+
38+ # Process first location. Add a for-loop for multiple locations or weather models
39+ response = responses [0 ]
40+ print (f"Coordinates: { response .Latitude ()} °N { response .Longitude ()} °E" )
41+ print (f"Elevation: { response .Elevation ()} m asl" )
42+ print (f"Timezone difference to GMT+0: { response .UtcOffsetSeconds ()} s" )
43+
44+ # Process hourly data. The order of variables needs to be the same as requested.
45+ hourly = response .Hourly ()
46+ hourly_temperature_2m = hourly .Variables (0 ).ValuesAsNumpy ()
47+
48+ hourly_data = {
49+ "date" : pd .date_range (
50+ start = pd .to_datetime (hourly .Time (), unit = "s" , utc = True ),
51+ end = pd .to_datetime (hourly .TimeEnd (), unit = "s" , utc = True ),
52+ freq = pd .Timedelta (seconds = hourly .Interval ()),
53+ inclusive = "left"
54+ )
55+ }
56+
57+ hourly_data ["temperature_2m" ] = hourly_temperature_2m .tolist ()
58+
59+ # Convert pandas Timestamp objects to ISO strings for JSON serialization
60+ hourly_data ["date" ] = [d .isoformat () for d in hourly_data ["date" ]]
61+
62+ return {
63+ "latitude" : response .Latitude (),
64+ "longitude" : response .Longitude (),
65+ "elevation" : response .Elevation (),
66+ "timezone" : response .Timezone (),
67+ "timezone_abbreviation" : response .TimezoneAbbreviation (),
68+ "utc_offset_seconds" : response .UtcOffsetSeconds (),
69+ "hourly" : hourly_data
70+ }
0 commit comments