1

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()
Chris
  • 18,724
  • 6
  • 46
  • 80
brinst
  • 11
  • 1
  • hmm... I took your advice and solved the problem I think. But it doesn't work. The problem I fixed was: Added \n to response data. And added nosniff to the header. but still not working plz help... – brinst May 12 '23 at 08:44

0 Answers0