Mercurial > personal > weather-server
diff 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 |
line wrap: on
line diff
--- a/weather_server/common.py Sun Sep 29 20:42:11 2019 -0400 +++ b/weather_server/common.py Sun Oct 06 13:11:11 2019 -0400 @@ -1,3 +1,5 @@ +import datetime +import json import typing as t import bson @@ -9,3 +11,22 @@ def bson_encode(data: t.Dict[str, t.Any]) -> bytes: return bson.BSON.encode(data, codec_options=BSON_OPTIONS) + + +class DateEncoder(json.JSONEncoder): + + def default(self, o: t.Any) -> t.Any: + if not isinstance(o, datetime.datetime): + return super().default(o) + return o.timestamp() + + +JSON_ENCODER = DateEncoder(sort_keys=True) + + +def json_dumps(data: t.Any) -> str: + return JSON_ENCODER.encode(data) + + +def utc_now(): + return datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)