wttr.in/lib/view/prometheus.py

65 lines
1.7 KiB
Python
Raw Normal View History

"""
Rendering weather data in the Prometheus format.
"""
from datetime import datetime
2020-06-12 17:12:08 +00:00
from fields import DESCRIPTION
2020-06-12 17:12:08 +00:00
def _render_current(data, for_day="current"):
"Converts data into prometheus style format"
2020-06-12 17:12:08 +00:00
output = []
2020-06-12 17:12:08 +00:00
for field_name, val in DESCRIPTION.items():
2020-06-12 17:12:08 +00:00
help, name = val
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
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 17:12:08 +00:00
description = ""
try:
2020-06-12 17:12:08 +00:00
float(value)
except ValueError:
description = f", description=\"{value}\""
value = "1"
2020-06-12 17:12:08 +00:00
output.append(f"# HELP {name} {help}\n"
f"{name}{{forecast=\"{for_day}\"{description}}} {value}")
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
def render_prometheus(data):
"""
Convert `data` into Prometheus format
2020-06-10 11:17:19 +00:00
and return it as string.
"""
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