Mercurial > personal > weather-server
view weather_server/locations.py @ 9:f1ea183d28ba
Give a 404 rather than a 500 on missing locations.
author | Paul Fisher <paul@pfish.zone> |
---|---|
date | Sun, 29 Sep 2019 20:34:38 -0400 |
parents | f66df122f18d |
children | beb42c835c52 |
line wrap: on
line source
"""Manages the directory containing the various logs.""" import configparser import pathlib import typing as t import attr import pytz from . import logfile from . import types CONFIG_FILE = 'config.ini' LOG = 'log.bson' @attr.s(frozen=True, slots=True) class LocationInfo: name = attr.ib(type=str) tz_name = attr.ib(type=str) password = attr.ib(type=str) def timezone(self): try: return pytz.timezone(self.tz_name) except pytz.UnknownTimeZoneError: return pytz.UTC @classmethod def load(cls, config_file: pathlib.Path) -> 'LocationInfo': parser = configparser.ConfigParser(interpolation=None) parser.read(config_file) return LocationInfo( name=parser.get('location', 'name', fallback='Weather station'), tz_name=parser.get('location', 'timezone', fallback='UTC'), password=parser.get('location', 'password')) class Locations: def __init__(self, base: str): self._path = pathlib.Path(base) def paths(self) -> t.Tuple[str, ...]: return tuple(sorted(f.name for f in self._path.iterdir())) def get(self, name) -> t.Tuple[LocationInfo, logfile.Logger]: try: directory = self._path / name logger = logfile.Logger.create(str(directory / LOG)) return (LocationInfo.load(directory / CONFIG_FILE), logger) except OSError: raise KeyError(name)