Mercurial > personal > weather-server
diff weather_server/server.py @ 21:beb42c835c52
Make weather server handle arbitrary data:
- Make logfile record arbitrary BSONs
- Make server handlers OK with same
- Make location type a normal class rather than attrs;
have it handle its own logger.
- Bump version number.
author | Paul Fisher <paul@pfish.zone> |
---|---|
date | Sat, 19 Oct 2019 18:40:48 -0400 |
parents | 9a609bcf0809 |
children | 88249e451566 |
line wrap: on
line diff
--- a/weather_server/server.py Sun Oct 13 18:44:12 2019 -0400 +++ b/weather_server/server.py Sat Oct 19 18:40:48 2019 -0400 @@ -1,17 +1,18 @@ import datetime import hmac +import pathlib import sys import bson import flask +import pytz from . import common from . import locations -from . import types def build_app(root_directory: str) -> flask.Flask: - locs = locations.Locations(root_directory) + locs = locations.LocationFolder(pathlib.Path(root_directory)) app = flask.Flask(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 @@ -32,35 +33,27 @@ preamble = next(reader) loc_name = preamble['location'] password = str(preamble['password']) - loc, logger = locs.get(loc_name) + loc = locs.get(loc_name) if not hmac.compare_digest(password, loc.password): flask.abort(400) - entries = [ - types.Reading.from_now( - sample_time=item['sample_time'], - temp_c=item['temp_c'], - rh_pct=item['rh_pct'], - ) - for item in reader - ] + entries = tuple(reader) except (KeyError, bson.InvalidBSON): flask.abort(400) - logger.write_rows(entries) + now = datetime.datetime.now(tz=pytz.UTC) + loc.record(entries, now) return flask.jsonify({'status': 'OK'}) @app.route('/<location>') def show(location: str): try: - loc, logger = locs.get(location) + loc = locs.get(location) except KeyError: flask.abort(404) - data = logger.data - if data: - last_reading = data[-1] + last_reading = loc.latest() + if last_reading: tz = loc.timezone() date = tz.normalize(last_reading.sample_time.astimezone(tz)) else: - last_reading = None date = None return flask.render_template( 'location.html', @@ -71,7 +64,7 @@ @app.route('/<location>/recent') def recent(location: str): try: - loc, logger = locs.get(location) + loc = locs.get(location) except KeyError: flask.abort(404) req = flask.request @@ -83,10 +76,7 @@ start = common.utc_now() - datetime.timedelta(seconds=seconds) - readings = [ - r.as_dict() for r in logger.data - if start < r.sample_time - ] + readings = [r for r in loc.entries if start < r['sample_time']] resp = flask.Response() resp.content_type = 'application/json' resp.data = common.json_dumps({