wttr.in/lib/view/prometheus.py

70 lines
1.9 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
def _render_current(data, for_day="current", already_seen=[]):
2020-06-12 17:12:08 +00:00
"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"
if name not in already_seen:
output.append(f"# HELP {name} {help}")
already_seen.append(name)
output.append(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.
"""
already_seen = []
answer = _render_current(
data["current_condition"][0], already_seen=already_seen)
2020-06-12 17:12:08 +00:00
for i in range(3):
answer += _render_current(
data["weather"][i], for_day="%sd" % i, already_seen=already_seen)
2020-06-12 17:12:08 +00:00
return answer