~pvsr/weather

weather/location.py -rw-r--r-- 1.9 KiB View raw
db8a58a0Peter Rice Reduce temperature graph from 48 to 36 hours 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import configparser
import json

from typing import Mapping

import requests
from cachecontrol import CacheControl  # type: ignore

REQUEST_CACHE = CacheControl(requests.session())

BASE_URL = "https://api.weather.gov"

class Location:
    short_name: str
    long_name: str
    forecast_url: str
    hourly_forecast_url: str
    alert_url: str

    def __init__(self, short_name: str, long_name: str, latitude: float, longitude: float):
        self.short_name = short_name
        self.long_name = long_name

        trunc = lambda f: format(f, '.4f')
        url = f"{BASE_URL}/points/{trunc(latitude)},{trunc(longitude)}"
        data = fetch_json(url, 'point')['properties']

        self.forecast_url = data['forecast']
        self.hourly_forecast_url = data['forecastHourly']
        # TODO really?
        self.alert_url = data['forecastZone'].replace('/zones/forecast', '/alerts/active/zone')

    def hourly(self):
        return fetch_json(self.hourly_forecast_url, 'hourly')

    def forecast(self):
        return fetch_json(self.forecast_url, 'forecast')

    def alerts(self):
        return fetch_json(self.alert_url, 'alerts')


LOCAL = False
def fetch_json(url: str, default: str):
    if LOCAL:
        with open(default, 'r') as local_data:
            return json.load(local_data)
    else:
        # print(f"requesting {url}")
        resp = REQUEST_CACHE.get(url)
        # print(resp)
        return resp.json()


def read_locations() -> Mapping[str, Location]:
    conf = configparser.ConfigParser()
    conf.read('locations.ini')
    result = {}
    for long_name in conf.sections():
        section = conf[long_name]
        result[long_name] = Location(long_name,
                                     section.get('long_name', long_name),
                                     section.getfloat('latitude'),
                                     section.getfloat('longitude'))
    return result