1313class Command (BaseCommand ):
1414 help = 'Add minimum, maximum and Average temperature of country temperature data from source api'
1515
16- def add_arguments (self , parser ):
17- parser .add_argument (
18- '--start_date' ,
19- action = 'store' ,
20- help = 'Start date to fetch temperature data in the format YYYY-MM-DD'
21- )
22- parser .add_argument (
23- '--end_date' ,
24- action = 'store' ,
25- help = 'End date to fetch temperature data in the format YYYY-MM-DD'
26- )
2716
2817 def handle (self , * args , ** options ):
29- for co in CountryOverview .objects .filter (country__record_type = CountryType .COUNTRY ).all ():
30- centroid = getattr (co .country , 'centroid' , None )
31- if centroid :
32- centroid = json .loads (centroid .geojson )
33-
34- lat = centroid .get ("coordinates" , [])[1 ]
35- lon = centroid .get ("coordinates" , [])[0 ]
36- if options ['start_date' ] and options ['end_date' ]:
37- response = requests .get (f'https://archive-api.open-meteo.com/v1/archive?latitude={ lat } &longitude={ lon } &start_date={ options ["start_date" ]} &end_date={ options ["end_date" ]} &daily=temperature_2m_max,temperature_2m_min,temperature_2m_mean,precipitation_sum,precipitation_hours' )
38- else :
39- response = requests .get (f'https://archive-api.open-meteo.com/v1/archive?latitude={ lat } &longitude={ lon } &start_date=2023-01-01&end_date=2023-12-31&daily=temperature_2m_max,temperature_2m_min,temperature_2m_mean,precipitation_sum,precipitation_hours' )
40- if response .status_code != 200 :
41- continue
18+ for co in CountryOverview .objects .filter (country__record_type = CountryType .COUNTRY , country__iso3__isnull = False ).all ():
19+ country_iso3 = co .country .iso3
20+ if country_iso3 :
21+ response = requests .get (f'https://climateknowledgeportal.worldbank.org/api/v1/cru-x0.5_climatology_tasmin,tas,tasmax,pr_climatology_monthly_1991-2020_mean_historical_cru_ts4.07_mean/{ country_iso3 } ?_format=json' )
4222 response .raise_for_status ()
43- try :
44- data = response .json ()
45- daily_data = data .get ('daily' , {})
46- if daily_data :
47- monthly_temperatures = defaultdict (list )
48-
49- for i , date_str in enumerate (daily_data .get ('time' , [])):
50- max_temp = daily_data .get ('temperature_2m_max' )[i ]
51- min_temp = daily_data .get ('temperature_2m_min' )[i ]
52- precipitation = daily_data .get ('precipitation_sum' )[i ]
53- if date_str and max_temp is not None and min_temp is not None :
54- date = datetime .strptime (date_str , '%Y-%m-%d' )
55- month_key = (date .year , date .month )
56- monthly_temperatures [month_key ].append ((max_temp , min_temp , precipitation ))
57- # Calculate min, max, and avg temperatures for each month
58- for month_key , temps in monthly_temperatures .items ():
59- year , month = month_key
60- max_temp_monthly = max (temps , key = lambda x : x [0 ])[0 ]
61- min_temp_monthly = min (temps , key = lambda x : x [1 ])[1 ]
62- avg_temp_monthly = (max_temp_monthly + min_temp_monthly ) / 2
63- precipitation_monthly = sum ([x [2 ] for x in temps ])
64-
23+ try :
24+ response_data = response .json ()
25+ data = response_data .get ('data' , {})
26+ if data :
27+ precipation = data .get ('pr' , {})
28+ average_temp = data .get ('tas' , {})
29+ min_temp = data .get ('tasmin' , {})
30+ max_temp = data .get ('tasmax' , {})
31+ merged_data = {
32+ country : {
33+ date : (precipation [country ][date ], average_temp [country ][date ], min_temp [country ][date ], max_temp [country ][date ])
34+ for date in precipation [country ]
35+ } for country in precipation
36+ }
37+ for key , value in merged_data .items ():
38+ for k , v in value .items ():
39+ year_month = k .split ('-' )
40+ data = {
41+ 'year' : year_month [0 ],
42+ 'month' : year_month [1 ],
43+ 'max_temp' : v [3 ],
44+ 'min_temp' : v [2 ],
45+ 'avg_temp' : v [1 ],
46+ 'precipitation' :v [0 ]
47+ }
6548 CountryKeyClimate .objects .create (
6649 overview = co ,
67- year = year ,
68- month = month ,
69- max_temp = max_temp_monthly ,
70- min_temp = min_temp_monthly ,
71- avg_temp = avg_temp_monthly ,
72- precipitation = precipitation_monthly
50+ ** data
7351 )
74- logger .info ('Minimum, maximum and Average temperature of country temperature data added successfully' )
75-
76- except Exception as ex :
77- logger .error (f'Error in ingesting climate data: { ex } ' )
78- continue
52+ except Exception as ex :
53+ logger .error (f'Error in ingesting climate data' ,exc_info = True )
54+ continue
0 commit comments