"""HTTP
This file tests the capabilities of an HTTP python client.
This file can be imported as a module and contains the following classes:
* HTTPHandler: The main handler for the HTTP requests.
"""
import os
import asyncio
import json
import warnings
from requests import post
from requests.exceptions import ConnectionError
warnings.filterwarnings("ignore")
[docs]
class HTTPHandler:
"""
Class for sending updates to the webinterface via HTTP Requests.
"""
_PROTOCOL_FORMAT = "http://{}:{}{}"
_HOST = os.environ.get('HOST_IP')
_PORT = 5000
_UPDATE_ENDPOINT = "/api/update"
_CONTENT_TYPE = "application/json"
_MAX_TIMEOUT = 10
__slots__ = ("_url",)
def __init__(self):
self._url = self._PROTOCOL_FORMAT.format(self._HOST, self._PORT, self._UPDATE_ENDPOINT)
[docs]
def update_webinterface(self, msg: str):
"""
Asynchronously send an update message to the webinterface via an HTTP POST request.
:param msg: The message you wish to send.
:type msg: str
"""
asyncio.run(self.send_message(msg))
[docs]
async def send_message(self, msg: str):
"""
Send an update message to the webinterface via an HTTP POST request.
:param msg: The message you wish to send.
:type msg: str
"""
try:
request_body = json.dumps({"body": {"message": msg}})
post(self._url, data = request_body,
headers = {"Content-type": self._CONTENT_TYPE},
timeout = self._MAX_TIMEOUT)
except ConnectionError:
pass