Skip to content

Commit

Permalink
fix: reads from other thread stdout (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
edeckers authored Mar 10, 2022
1 parent 4a5ac7e commit 3a1edbe
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/huemon/api_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import contextlib
import io
import threading
from typing import List

from fastapi import FastAPI, HTTPException, Query, Response, status
Expand All @@ -17,22 +18,25 @@


class HuemonServerFactory: # pylint: disable=too-few-public-methods
__stdout_reader_mutex = threading.Lock()

@staticmethod
def __create_command_route_handler(command_handler, command_name: str):
empty_query = Query([])

def handle_command_route(
q: List[str] = empty_query,
): # pylint: disable=invalid-name
context_reader = io.StringIO()
with contextlib.redirect_stdout(context_reader):
try:
command_handler.exec(command_name, q)
except SystemExit as system_exit:
raise HTTPException(
detail=context_reader.getvalue(),
status_code=status.HTTP_400_BAD_REQUEST,
) from system_exit
with HuemonServerFactory.__stdout_reader_mutex:
context_reader = io.StringIO()
with contextlib.redirect_stdout(context_reader):
try:
command_handler.exec(command_name, q)
except SystemExit as system_exit:
raise HTTPException(
detail=context_reader.getvalue(),
status_code=status.HTTP_400_BAD_REQUEST,
) from system_exit

return Response(context_reader.getvalue(), media_type="plain/text")

Expand Down

0 comments on commit 3a1edbe

Please sign in to comment.