2020-06-09 21:11:11 +00:00
|
|
|
"""
|
|
|
|
Rendering weather data in the Prometheus format.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2020-06-12 12:19:47 +00:00
|
|
|
from datetime import datetime
|
|
|
|
|
2020-06-12 17:12:08 +00:00
|
|
|
from fields import DESCRIPTION
|
2020-06-09 21:11:11 +00:00
|
|
|
|
2020-06-12 17:12:08 +00:00
|
|
|
def _render_current(data, for_day="current"):
|
|
|
|
"Converts data into prometheus style format"
|
2020-06-10 19:52:39 +00:00
|
|
|
|
2020-06-12 17:12:08 +00:00
|
|
|
output = []
|
2020-06-12 12:19:47 +00:00
|
|
|
|
2020-06-12 17:12:08 +00:00
|
|
|
for field_name, val in DESCRIPTION.items():
|
2020-06-12 12:19:47 +00:00
|
|
|
|
2020-06-12 17:12:08 +00:00
|
|
|
help, name = val
|
2020-06-09 21:11:11 +00:00
|
|
|
|
|
|
|
try:
|
2020-06-12 17:12:08 +00:00
|
|
|
value = data[field_name]
|
|
|
|
if field_name == "weatherDesc":
|
|
|
|
value = value[0]["value"]
|
|
|
|
except (IndexError, KeyError):
|
|
|
|
try:
|
|
|
|
value = data["astronomy"][0][field_name]
|
|
|
|
if value.endswith(" AM") or value.endswith(" PM"):
|
|
|
|
value = _convert_time_to_minutes(value)
|
|
|
|
except (IndexError, KeyError, ValueError):
|
|
|
|
continue
|
2020-06-12 12:19:47 +00:00
|
|
|
|
|
|
|
try:
|
2020-06-12 17:12:08 +00:00
|
|
|
if name == "observation_time":
|
|
|
|
value = _convert_time_to_minutes(value)
|
|
|
|
except ValueError:
|
|
|
|
continue
|
2020-06-12 12:19:47 +00:00
|
|
|
|
2020-06-12 17:12:08 +00:00
|
|
|
description = ""
|
2020-06-10 19:52:39 +00:00
|
|
|
try:
|
2020-06-12 17:12:08 +00:00
|
|
|
float(value)
|
|
|
|
except ValueError:
|
|
|
|
description = f", description=\"{value}\""
|
|
|
|
value = "1"
|
2020-06-09 21:11:11 +00:00
|
|
|
|
2020-06-12 17:12:08 +00:00
|
|
|
output.append(f"# HELP {name} {help}\n"
|
|
|
|
f"{name}{{forecast=\"{for_day}\"{description}}} {value}")
|
2020-06-12 12:19:47 +00:00
|
|
|
|
2020-06-09 21:11:11 +00:00
|
|
|
return "\n".join(output)+"\n"
|
|
|
|
|
2020-06-12 17:12:08 +00:00
|
|
|
def _convert_time_to_minutes(time_str):
|
|
|
|
"Convert time from midnight to minutes"
|
|
|
|
return int((datetime.strptime(time_str, "%I:%M %p")
|
|
|
|
- datetime.strptime("12:00 AM", "%I:%M %p")).total_seconds())//60
|
2020-06-12 12:19:47 +00:00
|
|
|
|
2020-06-09 21:11:11 +00:00
|
|
|
def render_prometheus(data):
|
|
|
|
"""
|
|
|
|
Convert `data` into Prometheus format
|
2020-06-10 11:17:19 +00:00
|
|
|
and return it as string.
|
2020-06-09 21:11:11 +00:00
|
|
|
"""
|
|
|
|
|
2020-06-12 17:12:08 +00:00
|
|
|
answer = _render_current(data["current_condition"][0])
|
|
|
|
for i in range(3):
|
|
|
|
data2 = data["weather"][i]
|
|
|
|
answer += _render_current(data2, for_day="%sd" % i)
|
|
|
|
return answer
|