~pvsr/weather

ref: e39316620448a8f20bc81da7de4bdfe1238c2c5e weather/location.py -rw-r--r-- 1.9 KiB
e3931662Peter Rice add an entry for minneapolis 1 year, 10 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"
LOCAL = False

class Location:
    short_name: str
    long_name: str
    forecastUrl: str
    hourlyForecastUrl: str
    alertUrl: 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')
        api = f"{BASE_URL}/points/{trunc(latitude)},{trunc(longitude)}"
        if LOCAL:
            with open('point', 'r') as f:
                data = json.load(f)['properties']
        else:
            data = request_cache.get(api).json()['properties']
        self.forecastUrl = data['forecast']
        self.hourlyForecastUrl = data['forecastHourly']
        # TODO really?
        self.alertUrl = data['forecastZone'].replace('/zones/forecast', '/alerts/active/zone')

    def hourly(self):
        if LOCAL:
            with open('hourly', 'r') as f:
                return json.load(f)
        req = request_cache.get(self.hourlyForecastUrl)
        return req.json()


    def forecast(self):
        if LOCAL:
            with open('forecast', 'r') as f:
                return json.load(f)
        req = request_cache.get(self.forecastUrl)
        return req.json()

    def alerts(self):
        if LOCAL:
            with open('alerts', 'r') as f:
                return json.load(f)
        req = request_cache.get(self.alertUrl)
        return req.json()


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