From e13ae89fcbd1543bf583e7a56f82ccaef4dfa8d4 Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Wed, 20 Jul 2016 23:08:54 +0300 Subject: Fix API post functionality --- project/shoutboxapicommunicator.py | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) (limited to 'project/shoutboxapicommunicator.py') diff --git a/project/shoutboxapicommunicator.py b/project/shoutboxapicommunicator.py index 4c7e0c0..c30b408 100644 --- a/project/shoutboxapicommunicator.py +++ b/project/shoutboxapicommunicator.py @@ -12,18 +12,30 @@ class ShoutboxCommunicator(BaseCommunicator): url = "http://localhost:8000" interval = 10 + @staticmethod + def get_url(): + return "{}/api/last?seconds={}".format(ShoutboxCommunicator.url, ShoutboxCommunicator.interval) + + @staticmethod + def post_url(): + return ShoutboxCommunicator.url + "/api/post" + @staticmethod def fetch(): """Get and return a list of new messages from the API""" try: - r = requests.get(ShoutboxCommunicator.url) + r = requests.get(ShoutboxCommunicator.get_url()) logging.info("Response from API OK.") except: - logging.warning("Failed to get response from API!") + logging.warning("Failed to get response from API! ({})".format(ShoutboxCommunicator.get_url())) return - content = json.loads(r.text) + try: + content = json.loads(r.text) + except: + logging.warning("Could not parse JSON from request!") + return if len(content) > 0: logging.info("Messages from shoutbox:") @@ -34,10 +46,14 @@ class ShoutboxCommunicator(BaseCommunicator): @staticmethod def send(data): - """Send a JSON message to the API""" + """Send a message to the API""" + post_params = "?user={}&text={}&id={}&ip={}×tamp={}".format( + data["user"], data["text"], data["id"], data["ip"], data["timestamp"] + ) + try: - requests.post(ShoutboxCommunicator.url, data) - user = json.loads(data)["user"] + requests.post(ShoutboxCommunicator.post_url() + post_params, "") + user = data["user"] logging.info("Sent message from {} to shoutbox.".format(user)) except: logging.warning("Failed to send message to shoutbox API!") -- cgit v1.3