I’m using tornado to create a websocket handler for my server, which execute a script and return output to client line by line. This is working fine until I make other requests to server while this part of websocket code is running. I’m not much proficient in asynchronous programming to find out issue in my code. Below is my handler code:
class EchoWebSocket(tornado.websocket.WebSocketHandler,tornado.web.RequestHandler):
def open(self):
print("WebSocket opened")
print("Request headers:", self.request)
params = self.request.uri.split('?')[-1]
self.param_pairs = {}
for pair in params.split('&'):
key, value = pair.split('=',1)
self.param_pairs[key] = value
print(f"Parameter {key}: {value}")
self.db_manager = DatabaseManager()
# connection = engine.connect()
def on_message(self, message):
self.write_message("Start")
self.stream_logs()
self.write_message("End")
def on_close(self):
print("WebSocket closed")
@coroutine
def stream_logs(self):
print("param pairs:", self.param_pairs)
#arg1=env-name/file-path arg2= python/yml
arg1=self.param_pairs['text1']
arg2=self.param_pairs['text2']
username = os.environ.get('XYZ')
if arg2=='yml':
command = f"grep -E '^name:' '/home/{arg1}' | awk '{{print $2}}'"
envnamedb = subprocess.check_output(command, shell=True, text=True)
else:
envnamedb= arg1
# async operation here
with subprocess.Popen(['bash', 'env.sh',arg1,arg2], cwd='/opt/data/shared', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, text=True) as process:
for line in process.stdout:
# Send each line of output in real-time over WebSocket
yield self.write_message(line)
exit_code = process.returncode
if exit_code == 0:
print('enter exit code')
if not self.db_manager.user_exists(username):
self.db_manager.insert_user(username)
if not self.db_manager.env_exists(envnamedb):
self.db_manager.insert_env(envnamedb,True,username)
yield self.write_message(json.dumps({"status": "success", "message": "Script execution succeeded."}))
else:
# Send failure response
yield self.write_message(json.dumps({"status": "failure", "message": "Script execution failed."}))
Please help me figure out where can I make changes in the code so that websocket call does not block other requests made to the server.