From e5d4e92939f9a28edb38a5d336cca9afbc46b0cf Mon Sep 17 00:00:00 2001 From: coolguy-cell Date: Wed, 10 Mar 2021 19:44:09 +0530 Subject: [PATCH] push-pull web service --- config.ini | 5 ++++ main.py | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 config.ini create mode 100644 main.py diff --git a/config.ini b/config.ini new file mode 100644 index 0000000..73b5935 --- /dev/null +++ b/config.ini @@ -0,0 +1,5 @@ + + +[server] +server_host = 127.0.0.1 +server_port = 8081 diff --git a/main.py b/main.py new file mode 100644 index 0000000..38ce090 --- /dev/null +++ b/main.py @@ -0,0 +1,76 @@ +import os +import sys + +import cherrypy +from cherrypy.lib.static import serve_file +import socket + +import configparser + +from pubsub import pub +import time + +PATH = os.path.dirname(os.path.abspath(__file__)) + +config = configparser.ConfigParser() +config.read("config.ini") +TIMEOUT = 60 #sec + + +class MainApp: + + def __init__(self): + self.received_data = None + + @cherrypy.expose + def submit(self, topic, data): + """ + This is where publisher can submit data + """ + pub.sendMessage(topic, data=data) + return "Published data to {}".format(topic) + + def msg_listener(self, data): + self.received_data = data + + + @cherrypy.expose + def poll(self, topic): + """ + Subscribers wait here for changes + """ + + pub.subscribe(self.msg_listener, topic) + + # wait for the data to come + rcv_data = self.received_data + s = time.time() + while not rcv_data and (time.time() - s) < TIMEOUT: + rcv_data = self.received_data + + if (time.time() - s) > TIMEOUT: + raise cherrypy.HTTPError(408, "Timeout Error. Publisher did not publish any data") + + self.received_data = None + pub.unsubscribe(self.msg_listener, topic) + return rcv_data + + +ROOT = MainApp() + +if __name__ == "__main__": + cherrypy.server.socket_host = config["server"].get("server_host", "127.0.0.1") + cherrypy.server.socket_port = config["server"].getint("server_port", 8081) + ENGINE = cherrypy.engine + + cherrypy.tree.mount(ROOT) + if hasattr(ENGINE, "signal_handler"): + ENGINE.signal_handler.subscribe() + if hasattr(ENGINE, "console_control_handler"): + ENGINE.console_control_handler.subscribe() + try: + ENGINE.start() + except Exception: + sys.exit(1) + else: + ENGINE.block()