Here is my problem that is partially resolved but not in the best way I think. I have a REST API Server that has a method POST that only executes a batch process. The method immediately returns 200 (without any body) and the batch process continues its task in the server. This batch process has a logging file, that I usually see online with tail -f mylogfile.log. What I want now is to use a websocket server to send the output of the tail process to webpage. The code of the websocket server look like this:
import os
import asyncio
import websockets
import subprocess
from frontserv.start_server import WEBSOCKET_INTERCHANGE_FILE
async def main(websocket, path):
print("-> STARTING")
exists = os.path.isfile(WEBSOCKET_INTERCHANGE_FILE)
if not exists:
f = open(WEBSOCKET_INTERCHANGE_FILE, "w+")
f.close()
exe = ["tail", "-f", WEBSOCKET_INTERCHANGE_FILE]
message = ""
p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=None)
while True:
retcode = p.poll()
print(message)
message = message + p.stdout.readline().decode("utf-8") + "<br>"
await websocket.send(message)
await asyncio.sleep(0.1)
start_server = websockets.serve(main, '127.0.0.1', 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
I have access to the batch process code, and I think there is a better way to resolve this. If instead of logging to a file I could send a message to the websocket server to dispatch a message to the browser, I think it would be a better implementation.
Best regards!
from How to communicate my Rest Api Server with my Web Socket server
No comments:
Post a Comment