With eventlet, callback function invoked only after bg thread exit (python Flask)

Viewed 100

I am using Flask and Socketio. Here's a simplification of my code:

from flask import Flask, url_for, render_template, send_from_directory, request, redirect
from flask_socketio import SocketIO, emit, send


app = Flask(__name__)
socketio = SocketIO(app, async_mode='threading')
#socketio = SocketIO(app)  # using eventlet, don't write "async_mode='threading' or it will ignore eventlet


@socketio.on('xxx', namespace='/xxx')
def start_bg(cid):
    # eventlet.spawn(bg_conversion, cid)
    socketio.start_background_task(bg_conversion, cid) # Do some time-consuming things
    print('test')

if __name__ == '__main__':
    socketio.run(app, port=80)

It works fine without eventlet, but now I have the need to stop a thread so I guess eventlet would be good.

However, if I switch to the annotated code, the client side's callback function will only be invoked after the thread(bg_conversion) exits.

I added a print after the spawning line, and it prints immediately - so it is running in the background. But why isn't the callback function on the client's side invoked immediately? Doesn't the function return immediately after the print?

0 Answers
Related