Mercurial > personal > weatherlog
view weatherlog/http_writer.py @ 18:9daa281d996b
Add a HTTP timeout, and verify the server response.
author | Paul Fisher <paul@pfish.zone> |
---|---|
date | Thu, 16 Jan 2020 23:52:30 -0500 |
parents | c01f9929ae38 |
children |
line wrap: on
line source
"""RemoteWriter which writes BSON to the given HTTP destination.""" import typing as t import requests from . import logger TIMEOUT_SECS = 60 class HTTPWriter(logger.RemoteWriter): def __init__(self, url: str, preamble: t.Dict[str, object]): self._url = url self._session = requests.Session() self._session.headers['User-Agent'] = 'weatherlogger/0.0.1' self._preamble = logger.bson_encode(preamble) def write(self, readings: t.Iterable[t.Dict[str, object]]) -> None: try: data = b''.join(map(logger.bson_encode, readings)) response = self._session.post( self._url, data=self._preamble + data, timeout=TIMEOUT_SECS) response.raise_for_status() contents = response.json() if contents.get('status') != 'OK': raise logger.RemoteWriteError( f'Invalid server response: {contents!r}') except requests.exceptions.RequestException as rex: raise logger.RemoteWriteError("Coulndn't write values") from rex except ValueError as ve: raise logger.RemoteWriteError('Invalid JSON response') from ve