I am trying to build a web based simulation. The simulation is triggered by GET request on one of the flask routes. Lets say:
@app.route("/start_simulation")
def start():
# First approach
# I dont like this approach as this view fuction wont
# return anything until simulation is completed
simulation = Simulator()
simulation.start('all required parameters') # this may take hours
return {"message": "simulation started"}
# Second approach
# Or I can spawn a new process and start the simulation in background.
create_new_process(simulation.start('all required parameters')) # This returns immediately
return {"message": "simulation started"}
Also, I want to send simulation progress/updates/graphs to the user via socketio. For this I am using flask_socketio module. Here is the initialization:
from flask import Flask
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
Best case would be send the updates from within the simulation.start()
method. Here is the implementation:
from api import socketio
class Simulator:
def __init__(self):
# Init part....
def start(self, 'all required parameters'):
for i in some_big_list:
# Do some operations
socketio.emit("status", data)
When I am using the first approach in which view function wont return anything until simulation is completed, all the socketio.emit messages are being recieved in the end (after simulation is finished).
When using second method of spawing a new process, no emit messages are received even after the simulation is completed.
Where am I going wrong?
I am expecting to receive the emitted message from socketio.emit
the moment it is generated.
Aman Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.