comparison weather_server/server.py @ 1:f66df122f18d

get the skeleton of a webserver up?
author Paul Fisher <paul@pfish.zone>
date Sun, 29 Sep 2019 00:52:13 -0400
parents
children cda47993a193
comparison
equal deleted inserted replaced
0:efe7a1eff167 1:f66df122f18d
1 import bson
2 import flask
3
4 from . import common
5 from . import locations
6 from . import types
7
8
9 def build_app(root_directory: str) -> flask.Flask:
10 locs = locations.Locations(root_directory)
11 app = flask.Flask(__name__)
12
13 @app.route('/favicon.ico')
14 def favicon():
15 return flask.send_file('static/favicon.ico')
16
17 @app.route('/')
18 def home():
19 return 'Weather server'
20
21 @app.route('/_submit', methods=['POST'])
22 def submit():
23 req = flask.request
24 target = req.args.get('location')
25 if not target:
26 flask.abort(404)
27 try:
28 target_loc = locs.get(target)
29 except KeyError:
30 flask.abort(404)
31
32 password = req.args.get('password')
33 if password != target_loc.password:
34 flask.abort(401)
35
36 reader = bson.decode_file_iter(
37 req.stream, codec_options=common.BSON_OPTIONS)
38 entries = [
39 types.Reading.from_now(
40 sample_time=item['sample_time'],
41 temp_c=item['temp_c'],
42 rh_pct=item['rh_pct'],
43 )
44 for item in reader
45 ]
46 target_loc.logger.write_rows(entries)
47 return {'status': 'OK'}
48
49 @app.route('/<location>')
50 def show(location):
51 try:
52 loc, logger = locs.get(location)
53 except KeyError:
54 flask.abort(404)
55 data = logger.data
56 if data:
57 last_reading = data[-1]
58 tz = loc.timezone
59 date = tz.normalize(last_reading.sample_time.astimezone(tz))
60 else:
61 last_reading = None
62 date = None
63 return flask.render_template(
64 'location.html',
65 location=loc,
66 last_reading=last_reading,
67 date=date)
68
69 return app