I am pulling data from an API and outputting it in influx line format. However, sometimes there is data missing, Rather than supplying a null value, the API omits that field. That causes this code to die.
for serial in SERIALS[site]:
r = requests.get(f"{BASE_API_URL}/equipment/{site}/{serial}/data", {
'startTime': format_datetime_url(startTime),
'endTime': format_datetime_url(endTime),
'api_key': SETTING_API_KEY
},
timeout=REQUEST_TIMEOUT)
# Parse request
for value in r.json()['data']['telemetries']:
date = value['date']
print(
f'data,site={site},sn={serial} I_Temp={value["temperature"]},I_AC_Energy_WH={value["totalEnergy"]},I_AC_Power={value["totalActivePower"]} {to_unix_timestamp(date)}',
flush=False)
return True
This code dies with a KeyError if any of the fields in value
are missing. I can add in something like this just before the print statement:
if not 'temperature' in value:
value["temperature"] = ""
if not 'totalEnergy' in value:
value["totalEnergy"] = ""
if not 'totalActivePower' in value:
value["totalActivePower"] = ""
but is there a more elegant way?