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()