57 lines
2.0 KiB
Python
57 lines
2.0 KiB
Python
|
#!/usr/bin/env python3
|
||
|
from http.server import HTTPServer, BaseHTTPRequestHandler, HTTPStatus
|
||
|
import io
|
||
|
import socket
|
||
|
import urllib.request
|
||
|
import xml.etree.ElementTree as ET
|
||
|
|
||
|
class HTTPServerV6(HTTPServer):
|
||
|
address_family = socket.AF_INET6
|
||
|
|
||
|
|
||
|
class ExporterRequestHandler(BaseHTTPRequestHandler):
|
||
|
def do_GET(self):
|
||
|
if self.path == "/":
|
||
|
self.make_response("Waldbrandgefahrenstufen Exporter für Brandenburg")
|
||
|
elif self.path == "/metrics":
|
||
|
self.export()
|
||
|
else:
|
||
|
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
|
||
|
return
|
||
|
|
||
|
def do_HEAD(self):
|
||
|
if self.path == "/":
|
||
|
self.make_response("Waldbrandgefahrenstufen Exporter für Brandenburg", head_only=True)
|
||
|
elif self.path == "/metrics":
|
||
|
self.export(head_only=True)
|
||
|
else:
|
||
|
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
|
||
|
return
|
||
|
|
||
|
def export(self, head_only=False):
|
||
|
r = []
|
||
|
with urllib.request.urlopen("https://mluk.brandenburg.de/mluk/de/wgs.xml") as f:
|
||
|
tree = ET.parse(f)
|
||
|
root = tree.getroot()
|
||
|
for lk in root[0].findall("landkreis"):
|
||
|
r.append('waldbrandgefahrenstufe{{landkreis="{landkreis}"}} {value}'.format(landkreis=lk.attrib["name"], value=lk.text))
|
||
|
self.make_response("\n".join(r), head_only=head_only)
|
||
|
|
||
|
def make_response(self, content, head_only=False):
|
||
|
encoded = content.encode("utf-8")
|
||
|
self.send_response(HTTPStatus.OK)
|
||
|
self.send_header("Content-Type", "text/plain; charset=utf-8")
|
||
|
self.send_header("Conten-Length", str(len(encoded)))
|
||
|
self.end_headers()
|
||
|
if not head_only:
|
||
|
self.wfile.write(encoded)
|
||
|
|
||
|
|
||
|
def run():
|
||
|
with HTTPServerV6(("::1", 9242), ExporterRequestHandler) as httpd:
|
||
|
print("Starting Waldbrandgefahrenstufen Exporter on http://[{}]:{}".format(*httpd.socket.getsockname()[:2]))
|
||
|
httpd.serve_forever()
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
run()
|