push-pull web service

This commit is contained in:
coolguy-cell 2021-03-10 19:44:09 +05:30
commit e5d4e92939
No known key found for this signature in database
GPG Key ID: CD3A42E1D470AD70
2 changed files with 81 additions and 0 deletions

5
config.ini Normal file
View File

@ -0,0 +1,5 @@
[server]
server_host = 127.0.0.1
server_port = 8081

76
main.py Normal file
View File

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