comparison weather_server/common.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 efe7a1eff167
children b77c8e7d2742
comparison
equal deleted inserted replaced
10:6d59f038a58b 11:52ef21607b31
1 import datetime
2 import json
1 import typing as t 3 import typing as t
2 4
3 import bson 5 import bson
4 import pytz 6 import pytz
5 7
7 tz_aware=True, tzinfo=pytz.UTC) 9 tz_aware=True, tzinfo=pytz.UTC)
8 10
9 11
10 def bson_encode(data: t.Dict[str, t.Any]) -> bytes: 12 def bson_encode(data: t.Dict[str, t.Any]) -> bytes:
11 return bson.BSON.encode(data, codec_options=BSON_OPTIONS) 13 return bson.BSON.encode(data, codec_options=BSON_OPTIONS)
14
15
16 class DateEncoder(json.JSONEncoder):
17
18 def default(self, o: t.Any) -> t.Any:
19 if not isinstance(o, datetime.datetime):
20 return super().default(o)
21 return o.timestamp()
22
23
24 JSON_ENCODER = DateEncoder(sort_keys=True)
25
26
27 def json_dumps(data: t.Any) -> str:
28 return JSON_ENCODER.encode(data)
29
30
31 def utc_now():
32 return datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)