1+ import requests
2+ import json
3+ import os
4+
5+ def get_formatted_month (month ):
6+
7+ if month < 10 :
8+ return '0' + str (month )
9+ return str (month )
10+
11+ def get_file_name (endpoint , year , start_month , end_month ):
12+
13+ return endpoint + str (year ) + '-' + get_formatted_month (start_month ) + '-' + \
14+ get_formatted_month (end_month ) + '.txt'
15+
16+ def get_api_records (endpoint , year , start_month , end_month ):
17+
18+ records = []
19+
20+ cache_filename = cache_filename = get_file_name (endpoint , year , start_month , end_month )
21+
22+ if os .path .exists (cache_filename ):
23+ with open (cache_filename ) as cache_file :
24+ records = json .load (cache_file )
25+ return records
26+
27+ record_count = 0
28+
29+ for month in range (start_month , end_month + 1 ):
30+
31+ formatted_month = get_formatted_month (month )
32+
33+ payload = {'key' :'sS8quPK7nt0ySnTFahzDP9VMlGhBqxIqjUKP6SUx' ,
34+ 'date' :'~' + str (year ) + '-' + str (formatted_month ),
35+ 'limit' :'none' }
36+
37+
38+ api_response = requests .get ('https://terraref.ncsa.illinois.edu/bety/api/beta/' + endpoint ,
39+ auth = ('nickheyek' , os .environ .get ('BETYdbPass' )),
40+ params = payload )
41+
42+ apiData = dict (api_response .json ())
43+
44+ records += apiData ["data" ]
45+ print (apiData ["metadata" ]["count" ])
46+ record_count += apiData ["metadata" ]["count" ]
47+
48+ with open (cache_filename , 'w' ) as cache_file :
49+ json .dump (records , cache_file )
50+
51+ return records
52+
53+ def get_trait_records (year , start_month , end_month ):
54+ return get_api_records ('traits' , year , start_month , end_month )
55+
56+ def get_management_records (year , start_month , end_month ):
57+ return get_api_records ('managements' , year , start_month , end_month )
0 commit comments