weather-exporter/main.py

80 lines
1.9 KiB
Python
Raw Normal View History

2021-06-21 20:41:01 +01:00
"""
Present observational weather data to Prometheus
"""
import json
import time
import os
import requests
from flask import Flask, Response
app = Flask(__name__)
def fetch_metoffice_data(location: int, apikey: str) -> dict:
"""
Fetch current data from the Met Office for the provided postcode
"""
obs_data = requests.get(
f'http://datapoint.metoffice.gov.uk/public/data/val/wxobs/all/json/{location}?'
f'key={apikey}&'
'res=hourly'
)
return json.loads(obs_data.content)
@app.route('/metrics')
def metrics():
"""
Output Prometheus-style metrics
"""
metoff_apikey = os.environ.get('METOFF_APIKEY')
metoff_location = os.environ.get('METOFF_LOCATION')
hour_data = fetch_metoffice_data(metoff_location, metoff_apikey,)['SiteRep']['DV'][
'Location'
]['Period'][-1]['Rep'][time.gmtime().tm_hour]
ret_data = [
{
2021-06-21 20:55:43 +01:00
'key': 'sensor_weather_outdoor_temperature_celsius',
2021-06-21 20:41:01 +01:00
'labels': {
'location': metoff_location,
},
'type': 'gauge',
'value': float(hour_data['T']),
},
{
'key': 'sensor_weather_outdoor_humidity_percent',
'labels': {
'location': metoff_location,
},
'type': 'gauge',
'value': float(hour_data['H']),
},
]
2021-06-21 21:43:46 +01:00
ret_strs = list()
2021-06-21 20:41:01 +01:00
for item in ret_data:
2021-06-21 21:43:46 +01:00
ret_strs.append(f'# HELP {item["key"]} Weather metric')
ret_strs.append(f'# TYPE {item["key"]} {item["type"]}')
ret_strs.append(
item["key"]
+ '{'
+ " ".join([f'{key}="{val}"' for key, val in item["labels"].items()])
+ '} '
+ str(item["value"])
)
resp = Response('\n'.join(ret_strs))
2021-06-21 20:41:01 +01:00
resp.headers['Content-type'] = 'text/plain'
return resp
if __name__ == '__main__':
app.run(host='0.0.0.0')