StreamingResponse of real time output of commands

57 Views Asked by At

I am developing an api that requests a command using FastAPI and receives the output for that command in real time. There is a problem, StreamingResponse seems to be working, but the output is returned once the command is finished, not every time the log is output in real time.

@app.post("/job")
async def create_job(cmd: Command):
    return StreamingResponse(cmdService.create_job(cmd), media_type='text/plain')

def create_job(cmd: Command):
    for output in cmdRepository.create_job(cmd):
        print(output)
        yield f"{output}"

def create_job(cmd: Command):
    p = subprocess.Popen(
        cmd.create_cmd(),
        stdout=PIPE,
        stderr=STDOUT,
        bufsize=1,
        universal_newlines=True
    )

    while True:
        output = p.stdout.readline()
        if not output and p.poll() is not None:
            break
        yield output.strip()
0

There are 0 best solutions below