Replace datetime.fromisoformat with dateutil

This commit is contained in:
Ben 2021-07-21 22:05:39 +02:00
parent 91bd738331
commit 3dd697755d
Signed by: ben
GPG Key ID: 0F54A7ED232D3319
3 changed files with 5 additions and 21 deletions

View File

@ -1,7 +1,7 @@
FROM docker.io/alpine:latest
MAINTAINER Benedikt Ziemons <ben@rs485.network>
RUN apk add --no-cache uwsgi-python3 python3 py3-yaml py3-flask py3-matrix-nio
RUN apk add --no-cache uwsgi-python3 python3 py3-yaml py3-flask py3-matrix-nio py3-dateutil
# partly from https://hub.docker.com/_/python?tab=description#create-a-dockerfile-in-your-python-app-project
WORKDIR /usr/src/wmn

View File

@ -1,3 +1,4 @@
PyYAML>=5.1,<6
flask[async]>=2.0.0,<3
matrix-nio[e2e]>=0.18.0,<1
python-dateutil~=2.8.2

23
wmn.py
View File

@ -28,6 +28,7 @@ import nio
import yaml
from flask import Flask, request, abort
from werkzeug.datastructures import MultiDict
import dateutil.parser
Cfg = Dict[str, Any]
ErrorResponse = Tuple[str, int]
@ -40,12 +41,6 @@ application = app
# Generally match room alias or id [!#]anything:example.com with unicode support.
room_pattern = re.compile(r"^[!#]\w+:[\w\-.]+$")
# older prometheus/alertmanager versions send too many sub-second digits in their timestamp,
# so we get rid of nanoseconds here
promtime_to_isotime_pattern = re.compile(
r"([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})(\.[0-9]{6})?(?:[0-9]{3})?(Z|[+-][0-9]{2}:[0-9]{2})"
)
def load_configuration() -> Cfg:
with open("config.yml", "r") as ymlfile:
@ -380,16 +375,6 @@ async def process_prometheus_request():
text = severity
return color_format_html(_severity_colors.get(severity, "FFFFFF"), text)
def parse_promtime(date_string) -> datetime:
match = promtime_to_isotime_pattern.match(date_string)
if match is None:
# weirdly enough, they switched to ISO primetime
return datetime.fromisoformat(date_string)
grps = list(filter(lambda x: x is not None, match.groups()))
if grps[-1] == "Z":
grps[-1] = "+00:00"
return datetime.fromisoformat("".join(grps))
def alert_title(status: str, alertname: str, generator_url: str):
if alertname:
alertname = " alert " + alertname
@ -430,14 +415,12 @@ async def process_prometheus_request():
alert_daterange = []
if "startsAt" in alert and alert["startsAt"] != "0001-01-01T00:00:00Z":
alert_start = (
parse_promtime(alert["startsAt"])
.strftime("%d. %b %y %H:%M %Z")
.rstrip()
dateutil.parser.isoparse(alert["startsAt"]).strftime("%d. %b %y %H:%M %Z").rstrip()
)
alert_daterange.append(f"started at {alert_start}")
if "endsAt" in alert and alert["endsAt"] != "0001-01-01T00:00:00Z":
alert_end = (
parse_promtime(alert["endsAt"]).strftime("%d. %b %y %H:%M %Z").rstrip()
dateutil.parser.isoparse(alert["endsAt"]).strftime("%d. %b %y %H:%M %Z").rstrip()
)
alert_daterange.append(f"ended at {alert_end}")
alert_daterange = ", ".join(alert_daterange)