I'm creating an optimization model with pyomo and trying to expose it via FastAPI (plain FastAPI or celery). In this process I'm trying to capture the solver output to stream it near-real-time to user to inspect it. To stream this data, I'm trying to use WebSockets
I've been using capture_output() but this doesn't seems to work.
Any hints to recommend or approach about how to handle this?
If I run uvicorn main:app --reload and open http://localhost:8000/ and push send button model start to solve and I'm able to stream the solver log into the template, but this only happen when the solving process had finish. For a much-larger model that takes long to solve, I want to watch the logs as near-real-time as possible.
Any hint on this or any other approach?
An example for this app can be as follows:
Structure
Main.py
template.py
This is only an .py file with an string with html data to stream WS
I finally could handle this. I'm not that sure that this is the best approach, but this works
Thanks to @Chris for the comment to This post.
I also used This answer to achieve this streaming
I decide to "stream" a "batch" of logs to avoid overhead since some solver (e.g., scip) generate a lot of verbose while optimizing, Then I stream a batch every 5 seconds.
I generate a class to stream replacing the sys.stdout. The method _write_by_batches generates a new event loop to allow asynchronously streaming throuth WebSocket generating a new event loop each time that log batch is streamed. Since I want to avoid overhead of streaming each time log
Then in the websocket endpoint, I get the running loop in order to run the solver.solve(instance, tee=True) using loop.run_in_executor.
The whole main.py script is as follows:
main.py