使用烧瓶的 socketio 扩展从线程发出

emitting from thread using flask's socketio extension

我想向套接字客户端发出延迟消息。例如,当一个新的客户端连接时,应该向客户端发送 "checking is started" 消息,并且在几秒钟后应该从线程发送另一条消息。

@socket.on('doSomething', namespace='/test')
def onDoSomething(data):
  t = threading.Timer(4, checkSomeResources)
  t.start()
  emit('doingSomething', 'checking is started')

def checkSomeResources()
  # ...
  # some work which takes several seconds comes here
  # ...
  emit('doingSomething', 'checking is done')

但是由于上下文问题,代码无法运行。我得到

RuntimeError('working outside of request context')

是否可以从线程发出信号?

问题是线程没有上下文,无法知道将消息发送给哪个用户。

您可以将request.namespace作为参数传递给线程,然后用它发送消息。示例:

@socket.on('doSomething', namespace='/test')
def onDoSomething(data):
    t = threading.Timer(4, checkSomeResources, request.namespace)
    t.start()
    emit('doingSomething', 'checking is started')

def checkSomeResources(namespace)
    # ...
    # some work which takes several seconds comes here
    # ...
    namespace.emit('doingSomething', 'checking is done')