changeset 10:b1657de734d5

Add HTTPWriter, which actually writes over HTTP.
author Paul Fisher <paul@pfish.zone>
date Sun, 29 Sep 2019 01:18:58 -0400
parents d8f38d992387
children 6dbd9825b3f5
files requirements.txt setup.py weatherlog/http_writer.py
diffstat 3 files changed, 27 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/requirements.txt	Sat Sep 28 20:21:35 2019 -0400
+++ b/requirements.txt	Sun Sep 29 01:18:58 2019 -0400
@@ -3,3 +3,4 @@
 attrs
 pymongo
 pytz
+requests
--- a/setup.py	Sat Sep 28 20:21:35 2019 -0400
+++ b/setup.py	Sun Sep 29 01:18:58 2019 -0400
@@ -11,6 +11,7 @@
         'attrs',
         'pymongo',
         'pytz',
+        'requests',
     ],
     setup_requires=['wheel'],
 )
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/weatherlog/http_writer.py	Sun Sep 29 01:18:58 2019 -0400
@@ -0,0 +1,25 @@
+"""RemoteWriter which writes BSON to the given HTTP destination."""
+
+import typing as t
+
+import bson
+import requests
+
+from . import logger
+from . import types
+
+
+class HTTPWriter(logger.RemoteWriter):
+
+    def __init__(self, url: str):
+        self._url = url
+        self._session = requests.Session()
+        self._session.headers['User-Agent'] = 'weatherlogger/0.0.1'
+
+    def write(self, readings: t.Sequence[types.Reading]) -> None:
+        try:
+            data = b''.join(bson.BSON.encode(r.as_dict()) for r in readings)
+            response = self._session.post(self._url, data=data)
+            response.raise_for_status()
+        except requests.exceptions.RequestException as rex:
+            raise logger.RemoteWriteError("Coulndn't write values") from rex