socketio的start_background_task函數用於新建一個線程,處理業務,在線程中在請求上下文中調用收發功能函數git
app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, async_mode=async_mode) def background_thread(): """Example of how to send server generated events to clients.""" count = 0 while True: socketio.sleep(10) count += 1 socketio.emit('my_response', {'data': 'Server generated event', 'count': count}, namespace='/test') @socketio.on('connect', namespace='/test') def test_connect(): global thread if thread is None: thread = socketio.start_background_task(target=background_thread) emit('my_response', {'data': 'Connected', 'count': 0})
來自flask-socketio官方github示例代碼github
https://github.com/miguelgrinberg/Flask-SocketIO/blob/master/example/app.pyflask
包括了基本的函數調用狀況,極具實用價值app