Mercurial > personal > weather-server
comparison weather_server/server.py @ 11:52ef21607b31
server: Create endpoint to get some recent readings.
author | Paul Fisher <paul@pfish.zone> |
---|---|
date | Sun, 06 Oct 2019 13:11:11 -0400 |
parents | d54155a199d8 |
children | 9a609bcf0809 |
comparison
equal
deleted
inserted
replaced
10:6d59f038a58b | 11:52ef21607b31 |
---|---|
1 import datetime | |
1 import hmac | 2 import hmac |
2 import sys | 3 import sys |
3 | 4 |
4 import bson | 5 import bson |
5 import flask | 6 import flask |
46 flask.abort(400) | 47 flask.abort(400) |
47 logger.write_rows(entries) | 48 logger.write_rows(entries) |
48 return flask.jsonify({'status': 'OK'}) | 49 return flask.jsonify({'status': 'OK'}) |
49 | 50 |
50 @app.route('/<location>') | 51 @app.route('/<location>') |
51 def show(location): | 52 def show(location: str): |
52 try: | 53 try: |
53 loc, logger = locs.get(location) | 54 loc, logger = locs.get(location) |
54 except KeyError: | 55 except KeyError: |
55 flask.abort(404) | 56 flask.abort(404) |
56 data = logger.data | 57 data = logger.data |
65 'location.html', | 66 'location.html', |
66 location=loc, | 67 location=loc, |
67 last_reading=last_reading, | 68 last_reading=last_reading, |
68 date=date) | 69 date=date) |
69 | 70 |
71 @app.route('/<location>/recent') | |
72 def recent(location: str): | |
73 try: | |
74 loc, logger = locs.get(location) | |
75 except KeyError: | |
76 flask.abort(404) | |
77 req = flask.request | |
78 | |
79 try: | |
80 seconds = int(req.args['seconds']) | |
81 except (KeyError, ValueError): | |
82 flask.abort(400) | |
83 | |
84 start = common.utc_now() - datetime.timedelta(seconds=seconds) | |
85 | |
86 readings = [ | |
87 r.as_dict() for r in logger.data | |
88 if start < r.sample_time | |
89 ] | |
90 resp = flask.Response() | |
91 resp.content_type = 'application/json' | |
92 resp.data = common.json_dumps(readings) | |
93 return resp | |
94 | |
70 return app | 95 return app |
71 | 96 |
72 | 97 |
73 def main(argv): | 98 def main(argv): |
74 """Main function for a simple local demo.""" | 99 """Main function for a simple local demo.""" |